Search code examples
c#textboxkeypress

How do I find the key code of a character in C#?


Microsoft provides a documentation for key codes of characters. For example, one can find that the key code for the delete key is 8 whereas the add key (+) has the key code 107. In a Windows Forms Application I'm trying to create a text box that will only accept digits and the plus sign (+). To do this I have implemented the following code:

private void ansBox_KeyPress(object sender, KeyPressEventArgs e)
{
   char ch = e.KeyChar;
   if (!Char.IsDigit(ch) && ch != 8 && ch != 107) e.Handled = true;
}

The code successfully disallows all input except for digits and deletion, but to my surprise blocks the use of the plus sing (+). This leads me to believe that "107" is not the key code for the plus sign in C# or that I've implemented the key codes incorrectly. Is there a way to find the key codes of characters programmatically similarly to how variable types can be identified so that the key code of the plus character can be determined? Alternatively, have I done something incorrectly when trying to implement the above described text box functionality?


Solution

  • KeyCode and KeyChar is not the same.

    KeyCode is a property of KeyEventArgs and provides data for the KeyDown and KeyUp events. It has the type Keys, which is an enum.

    KeyChar is a property of KeyPressEventArgs and provides data for the KeyPress event. It is a char.

    The numeric codes of the two are often different.

    You can simply test for the plus sign like this

    ch != '+'
    

    C# has an escape sequnce for Backspace ( '\b' == (char)8 )

    if (!Char.IsDigit(ch) && ch != '\b' && ch != '+') e.Handled = true;