How to determine if a key is a letter or number?

Ryan Peschel picture Ryan Peschel · Feb 26, 2012 · Viewed 9.9k times · Source

KeyboardState.GetPressedKeys() returns a Key array of currently pressed keys. Normally to find out if a key is a letter or number I would use Char.IsLetterOrDigit(char) but the given type is of the Keys enumeration and as a result has no KeyChar property.

Casting does not work either because, for example, keys like Keys.F5, when casted to a character, become the letter t. In this case, F5 would then be seen as a letter or digit when clearly it is not.

So, how might one determine if a given Keys enumeration value is a letter or digit, given that casting to a character gives unpredictable results?

Answer

max picture max · Feb 26, 2012
public static bool IsKeyAChar(Keys key)
{
    return key >= Keys.A && key <= Keys.Z;
}

public static bool IsKeyADigit(Keys key)
{
    return (key >= Keys.D0 && key <= Keys.D9) || (key >= Keys.NumPad0 && key <= Keys.NumPad9);
}