0
votes

I am currently in the middle of learning c# for my job, I have been trying some starter projects and i decided to make a calculator, I have all of the functions of a simple calculator working, however i can not get the numpad keys to work with a keypress event or a keydown event, I am wondering if someone can help me in some detail, i am wanting to sett all of the numpad keys to the corrspondings ones on the calculator, here is the code i have tried for the keypress event and i have also tried this with numpad lock on and off.

 private void n1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar = '1')
        {
            e.Handled = true;
            n1.PerformClick();

        }

    }

Just a quick edit, i have tried to follow MSDN example and include the following

private void n1_KeyDown(object sender, KeyEventArgs e) {

        if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
        {
            if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
            {
                nonNumberEntered = true;
            }
        }

And still no success

3
If reading the documentation is out of the question, use the F9 key to put a breakpoint on the if line in your code. Then try pressing a number-pad digit key and use the watch window to find out what e.KeyChar is equal to in that case. You can take a look at the other properties of e as well.15ee8f99-57ff-4f92-890c-b56153
Possible duplicate of Calculator keypressger
I have checked & with NumLock on - pressing the 1 key does result in getting a KeyPress event with the value of e.KeyChar equal to '1'.PaulF
Looking at your code I see the method is n1_KeyPress - do you have multiple buttons each with a key press event attached n2_, n3_ ...? The KeyPress event will only happen for the button that has focus.PaulF
So i did decide to re-write said code in a different form, and i still have no such luck, private void n1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.NumPad0 || e.KeyCode == Keys.D0) } }OnAngelsWings

3 Answers

1
votes

Refer to MSDN Key Enum page for reference.

e.g. Keys.NumPad0 is on keypad, Keys.D0 is the number key. So you want to do something like this

if (e.KeyCode == Keys.NumPad0 || e.KeyCode == Keys.D0)

And also you probably want to map the operators, e.g. Keys.Add for your add.

0
votes

Check what the equals operator should be.

if (e.KeyChar == '1')

(You won't be the last person to fall down that particular hole, trust me....)

0
votes

Try using a comparison instead of assigning.