16

Is there a way to determine if a key is letter/number (A-Z,0-9) in the KeyEventArgs? Or do I have to make it myself? I found a way with e.KeyCode, is that accurate?

if(((e.KeyCode >= Keys.A       && e.KeyCode <= Keys.Z )
 || (e.KeyCode >= Keys.D0      && e.KeyCode <= Keys.D9 )
 || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9))
slugster
  • 49,403
  • 14
  • 95
  • 145
Andr
  • 617
  • 2
  • 9
  • 24
  • 1
    How do you define letter? only A-Z or letters in other languages too? And the same for numbers. And a key is not even a char(there is no 1-to-1 correspondence between keys and characters), so it can't be a letter/number. – CodesInChaos Mar 13 '11 at 23:37
  • 3
    You cannot know this from the KeyDown event. Only after the virtual key is translated with the user's keyboard layout do you know. Use the KeyPressed event instead. – Hans Passant Mar 13 '11 at 23:57

4 Answers4

33

You can use the char.IsLetterOrDigit() method on the KeyCode of the event args:

bool isLetterOrDigit = char.IsLetterOrDigit((char) keyEventArgs.KeyCode);
adrianbanks
  • 81,306
  • 22
  • 176
  • 206
  • 1
    This does not actually seem to work on azerty numbers. They require shift to be pressed to access them, and I fear that the shift + whatever the actual key is does not get processed right by the Char tools. – Nyerguds Feb 25 '21 at 19:45
  • Does not work in vb.net. 'Keys' cannot be converted to 'Char' Weird – stigzler Jan 20 '22 at 15:21
9

Char.IsNumber() and Char.IsLetter()

Bala R
  • 107,317
  • 23
  • 199
  • 210
8

In WPF? Use PreviewTextInput or TextInput events instead of KeyDown

Tank Gamer
  • 81
  • 1
0

Char.IsLetter() accepts some of OEM key codes that was treated as alphabetical characters.

My case was when I typed a keyboard (tilde) then this Keycode was returned OEM3.

I inspected the value (tilde) and it says

"192 'A'"

But actual typing 'A' was

"65 'A'"

As a result, both passed Char.IsLetter() as True.

To avoid this, I put below code.

private bool IsAlphabetOrDigit(System.Windows.Forms.KeyEventArgs e)
{
    var keyCode = (char)e.KeyCode;
    if ( false == char.IsNumber( keyCode ) &&  false == ((keyCode >= 'a' && keyCode <= 'z') || (keyCode >= 'A' && keyCode <= 'Z')))
    {
        return false;
    }

    return true;
}
Takeo Nishioka
  • 369
  • 2
  • 11