Can I determine if a KeyEventArg is an letter or number?
Asked Answered
J

4

17

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))
Joachima answered 13/3, 2011 at 23:35 Comment(2)
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.Chapin
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.Genuflection
G
33

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

bool isLetterOrDigit = char.IsLetterOrDigit((char) keyEventArgs.KeyCode);
Grope answered 13/3, 2011 at 23:40 Comment(2)
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.Caraviello
Does not work in vb.net. 'Keys' cannot be converted to 'Char' WeirdGaucho
P
10

In WPF? Use PreviewTextInput or TextInput events instead of KeyDown

Pyrophosphate answered 3/5, 2011 at 16:45 Comment(0)
P
9

Char.IsNumber() and Char.IsLetter()

Prolonge answered 13/3, 2011 at 23:37 Comment(2)
Lots of similar goodies in Char.Wise
Ok, didn't know that one! nice answer.Joachima
C
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;
}
Coset answered 14/8, 2020 at 5:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.