Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture multiple key downs in C#

Tags:

c#

winforms

How can I capture multiple key downs in C# when working in a Windows Forms form?

I just can't seem to get both the up arrow and right arrow at the same time.

like image 844
Presidenten Avatar asked Apr 02 '09 12:04

Presidenten


2 Answers

I think you'll be best off when you use the GetKeyboardState API function.

[DllImport ("user32.dll")]
public static extern int GetKeyboardState( byte[] keystate );


private void Form1_KeyDown(object sender, KeyEventArgs e)
{
   byte[] keys = new byte[256];

   GetKeyboardState (keys);

   if ((keys[(int)Keys.Up] & keys[(int)Keys.Right] & 128 ) == 128)
   {
       Console.WriteLine ("Up Arrow key and Right Arrow key down.");
   }
}

In the KeyDown event, you just ask for the 'state' of the keyboard. The GetKeyboardState will populate the byte array that you give, and every element in this array represents the state of a key.

You can access each keystate by using the numerical value of each virtual key code. When the byte for that key is set to 129 or 128, it means that the key is down (pressed). If the value for that key is 1 or 0, the key is up (not pressed). The value 1 is meant for toggled key state (for example, caps lock state).

For details see the Microsoft documentation for GetKeyboardState.

like image 154
Frederik Gheysels Avatar answered Oct 07 '22 07:10

Frederik Gheysels


A little proof-of-concept code for you, assuming Form1 contains label1:

private List<Keys> pressedKeys = new List<Keys>();

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    pressedKeys.Add(e.KeyCode);

    printPressedKeys();
}

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    pressedKeys.Remove(e.KeyCode);

    printPressedKeys();
}

private void printPressedKeys()
{
    label1.Text = string.Empty;
    foreach (var key in pressedKeys)
    {
        label1.Text += key.ToString() + Environment.NewLine;
    }
}
like image 27
Tormod Fjeldskår Avatar answered Oct 07 '22 08:10

Tormod Fjeldskår