Ryan Peschel
Ryan Peschel

Reputation: 11828

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

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?

Upvotes: 8

Views: 12529

Answers (3)

Douglas
Douglas

Reputation: 54897

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

Upvotes: 3

max
max

Reputation: 34427

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

Upvotes: 15

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

Have your own table/set of HashSets to map Keys enumeration to types your are interested.

There are only about hundred different values - so table will not be too big. If you worried about size in memory - it is one byte per enumeration value (if using a byte array indexed by Keys values).

Upvotes: 0

Related Questions