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

10,532

Solution 1

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);
}

Solution 2

Given that “digit keys” correspond to specific ranges within the Keys enumeration, couldn’t you just check whether your key belongs to any of the ranges?

Keys[] keys = KeyboardState.GetPressedKeys();
bool isDigit = keys.Any(key =>
    key >= Keys.D0      && key <= Keys.D9 || 
    key >= Keys.NumPad0 && key <= Keys.NumPad9);
Share:
10,532
Ryan Peschel
Author by

Ryan Peschel

Updated on June 15, 2022

Comments

  • Ryan Peschel
    Ryan Peschel almost 2 years

    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?

  • max
    max about 12 years
    Can't find it in Keys enumeration (msdn.microsoft.com/en-us/library/…)