Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

key

xna

xna-4.0

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?

like image 361
Ryan Peschel Avatar asked Feb 26 '12 18:02

Ryan Peschel


2 Answers

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);
}
like image 117
max Avatar answered Sep 19 '22 14:09

max


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);
like image 32
Douglas Avatar answered Sep 19 '22 14:09

Douglas