小编典典

在C#中捕获多个按键

c#

Windows窗体表单中工作时,如何捕获C#中的多个按键?

我似乎无法同时获得向上箭头和向右箭头。


阅读 759

收藏
2020-05-19

共1个答案

小编典典

我认为使用GetKeyboardState API函数将是最好的选择。

[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.");
   }
}

在KeyDown事件中,您只要求输入键盘的“状态”。GetKeyboardState将填充您提供的字节数组,并且该数组中的每个元素都代表键的状态。

您可以通过使用每个虚拟键控代码的数值来访问每个键控状态。当该键的字节设置为129或128时,表示该键已按下(按下)。如果该键的值为1或0,则该键向上(未按下)。值1表示切换键状态(例如,大写锁定状态)。

有关详细信息,请参见Microsoft文档GetKeyboardState

2020-05-19