Bad detection of my keyboard(C#)

Why when i click for example "a" on my keyboard program seems bad key "F8". Diffrent examples:

"1" = "NumPad7"   
"A" =  "V"
"B" = "W"

Problem is in:

label.Content = (Key)key;

When i change (Key) for (char) it works but only for a-z and A-Z keys. How can i properly detect my keyboard?

    public void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (condition == true)
        {
            int key;
            int keyState;
            for (key = 0; key < 127; key++)
            {
                keyState = GetAsyncKeyState(key);
                if (keyState == 1 || keyState == -32767)
                {
                    if(Keyboard.IsKeyDown(Key.LeftShift) || 
                     Keyboard.IsKeyDown(Key.RightShift ))
                    {
                        Save_With_Big_Letters(key);
                        label.Content = (Key)key;
                    }
                    else
                    {
                        Save_With_Small_Letters(key);
                        label.Content = (Key)(key + 32);
                    }
                }

            }
        }     
    }

Upvotes: 0

Views: 81

Answers (1)

rokkerboci
rokkerboci

Reputation: 1167

GetAsyncKeyState uses the older, WindowsForms key values. To make this work, either use System.Windows.Forms.Keys enum, or just use the KeyEventArgs.Key value.

Like this:

label.Content = (System.Windows.Forms.Keys)key;

or the better way:

label.Content = e.Key;

Upvotes: 2

Related Questions