8

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?

Ryan Peschel
  • 11,087
  • 19
  • 74
  • 136
  • You wish F5 to be flagged as a letter or a number? – Dharun Feb 26 '12 at 19:00
  • 1
    Look here http://stackoverflow.com/questions/5718541/check-if-keys-is-letter-digit-special-symbol – Kamil Feb 26 '12 at 19:04
  • @SwearWord: No. The problem is that when `Keys.F5` is casted to a character it becomes `t`. `Keys.F5` should fail the *is letter or number* test. – Ryan Peschel Feb 26 '12 at 19:06
  • [This thread](http://social.msdn.microsoft.com/forums/en-US/xnaframework/thread/d4ffe642-cf35-4ccd-92ab-0c0dfd17c95d/) from the MSDN XNA forums may be of help. – adrianbanks Feb 26 '12 at 19:11
  • @RyanPeschel are you interested in letters that would be typed when key is pressed or always English letters that directly correspond to `Keys`? If former Kamil's link provides good approach. – Alexei Levenkov Feb 26 '12 at 19:14
  • A Key is a Key, and not a number or letter. There is no simple mapping between keys and characters. – CodesInChaos Feb 26 '12 at 19:15

3 Answers3

14
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);
}
max
  • 33,369
  • 7
  • 73
  • 84
  • 2
    Can't find it in Keys enumeration (http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.keys.aspx) – max Feb 26 '12 at 19:22
3

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);
Douglas
  • 53,759
  • 13
  • 140
  • 188
0

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

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179