Reading NumPad keys using WinRT

January 28, 2015

Recently, I discovered a bug with one of my Windows Store games - Maths Races. The issue was that when a number key was pressed, the program works fine, but pressing a number pad key - even with NumLock on wasn’t recognised.

Here’s the code that I was using the detect the keypress:



KeyboardState newState = Keyboard.GetState();
var keys = newState.GetPressedKeys();

foreach (var key in keys)
{
    if (!IsNewKeyPressed(key))
        continue;

    byte keychar;
    if (byte.TryParse(key.GetHashCode().ToString(), out keychar))
    {
        char newChar = Convert.ToChar(keychar);

        if (Char.IsNumber(newChar))
        {
            . . . 

So, when I press a number pad key with Num Lock off, it behaves as though I’d pressed a different character; for example NumPad0 resolves to a key character code of 96:

(byte.TryParse(key.GetHashCode().ToString(), out keychar))

Which when converted to a char is ”`“.

Okay, so here’s how I got around this:



if (key.HasFlag(Keys.NumPad0 & Keys.NumPad1 & Keys.NumPad2 &
    Keys.NumPad3 & Keys.NumPad4 & Keys.NumPad5 & Keys.NumPad6 &
    Keys.NumPad7 & Keys.NumPad8 & Keys.NumPad9))
{
    char number = key.ToString().Substring(6)[0];
    . . .
}                
else
   . . .

Admittedly it isn’t very pretty, and if someone knows a better, or more elegant way to do this, then please let me know.



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024