Hi
How can I capture multiple key downs in C# when working in a windows form? I just cant seem to get both up arrow and right arrow at the same time.
Hi
How can I capture multiple key downs in C# when working in a windows form? I just cant seem to get both up arrow and right arrow at the same time.
hmm Are there seperate events for each key down?
Fast answer without looking into msdn:
You can create 4 booleans for each arrow. When is pressed set the boolean of that arrow to true if released is fire set the boolean of that arrow to false.
Then you can check with if the up and right boolean are true and then do your action.
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;
}
}
I think you'll be best of 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[255];
GetKeyboardState (keys);
if( keys[(int)Keys.Up] == 129 && keys[(int)Keys.Right] == 129 )
{
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, it means that the key is down. If the value for that key is 128, the key is up.
Use SPY++ to see how key downs are fired. Basically if multiple arrow keys are held down at the same time the first key that was hit will fire events then when the second key is hit it will begin firing and you will no longer see events for the first one. When they are released you'll see their key up events. I would suggest you implement the bool flags suggested earlier its quick and simple.