Naveen Kumar V
Naveen Kumar V

Reputation: 2809

Why are numeric keypad numbers and regular numbers not the same in KeyEvent?

This code does not allow me to enter numeric values from a numeric keypad.

private void textBox1_KeyDown( object sender, KeyEventArgs e ) {
    e.SuppressKeyPress = !( (e.KeyValue >= 48 && e.KeyValue <= 57) )
}

How can I include numerical values in general (both from regular and number keys)?

Upvotes: 3

Views: 3113

Answers (3)

Salah Akbari
Salah Akbari

Reputation: 39946

One solution is using the KeyPress event and TryParse method like this:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     int n;
     e.Handled = !int.TryParse(e.KeyChar.ToString(), out n);
}

Or you can check for NumPads like this:

e.SuppressKeyPress = !((e.KeyValue >= 48 && e.KeyValue <= 57 || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)));

Upvotes: 1

Luizgrs
Luizgrs

Reputation: 4873

Because after all they're different keys, even though the char they represent is the same.

To get a better result you can use the Keys enum and KeyCode property:

e.SuppressKeyPress = !((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9))

Or use KeyPress event because there you'll have char codes in the event args.

Inside a KeyPress event handler you can do:

 e.Handled = !Char.IsDigit(e.KeyChar)

Upvotes: 6

Dennisch
Dennisch

Reputation: 7523

They are not the same because they are not the same key. Keyvalue is an abstraction of the specific key you have pressed on the keyboard, not of the value that the key represents.

That said, you can simply check if either the numpad key or the other is pressed with a simple OR.

Upvotes: 1

Related Questions