Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does KeyChar for Delete return the same as for Period?

Tags:

c#

.net

I am catching a KeyPress-Event to check for certain kinds of allowed values. To be able to delete I am using following code before the actual check

if (e.KeyChar == (char)Keys.Delete || e.KeyChar == (char)Keys.Back)
{
   return;
}
...actual check for only digits or whatever

The problem is that e.KeyChar == (char)Keys.Delete is also true when I hit the period on my keyboard.

How can this be? And what could I do about it?

Thanks

like image 346
lostiniceland Avatar asked Dec 18 '22 05:12

lostiniceland


2 Answers

From MSDN documentation on the Keys enumeration:

The Keys class contains constants for processing keyboard input. The members of the Keys enumeration consist of a key code and a set of modifiers combined into a single integer value. In the Win32 application programming interface (API) a key value has two halves, with the high-order bits containing the key code (which is the same as a Windows virtual key code), and the low-order bits representing key modifiers such as the SHIFT, CONTROL, and ALT keys.

Converting these constants to char is meaningless, since you will lose valuable information and the constant values do not correspond to ASCII character codes.

From MSDN concerning the KeyChar property of KeyPressEventArgs:

You cannot get or set the following keys (...) INSERT and DELETE (...)

KeyChar returns the char value (ASCII character code) corresponding to pressed key, not its (raw) key code. Therefore you cannot detect various special keys and cannot compare the value to the Keys enumeration constants.

Use the KeyCode property of KeyEventArgs instead. Since it is of type Keys, not char, it is well suited for your purpose. In order to access this information, you will have to handle the KeyDown event instead of the KeyPress event.

By the way, according to the MSDN page on the Control KeyPress event, this event is not raised for non-character keys at all:

The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.

like image 71
Ferdinand Beyer Avatar answered Dec 19 '22 18:12

Ferdinand Beyer


Maybe you should compare with e.KeyCode instead. It's more precise and you won't need to convert Keys.Delete and Keys.Back to a char.

like image 22
Meta-Knight Avatar answered Dec 19 '22 20:12

Meta-Knight