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?
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);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With