How to determine if a key is a letter or number?
Asked Answered
C

3

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?

Commove answered 26/2, 2012 at 18:56 Comment(6)
You wish F5 to be flagged as a letter or a number?Sneakbox
Look here #5719041Kimberlite
@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.Commove
This thread from the MSDN XNA forums may be of help.Augsburg
@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.Sapphera
A Key is a Key, and not a number or letter. There is no simple mapping between keys and characters.Felicidad
S
15
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);
}
Spinoza answered 26/2, 2012 at 19:7 Comment(1)
Can't find it in Keys enumeration (msdn.microsoft.com/en-us/library/…)Spinoza
H
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);
Haihaida answered 26/2, 2012 at 19:14 Comment(0)
S
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).

Sapphera answered 26/2, 2012 at 19:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.