Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

winforms - Capture multiple key downs in C#

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...