How to determine if a key is a letter or number?
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);
Ryan Peschel
Updated on June 15, 2022Comments
-
Ryan Peschel almost 2 years
KeyboardState.GetPressedKeys()
returns aKey
array of currently pressed keys. Normally to find out if a key is a letter or number I would useChar.IsLetterOrDigit(char)
but the given type is of theKeys
enumeration and as a result has noKeyChar
property.Casting does not work either because, for example, keys like
Keys.F5
, when casted to a character, become the lettert
. 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 about 12 yearsCan't find it in Keys enumeration (msdn.microsoft.com/en-us/library/…)