在 C# 中捕获多个按键 [英] Capture multiple key downs in C#

查看:29
本文介绍了在 C# 中捕获多个按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Windows 窗体 表单中工作时,如何在 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.

推荐答案

我认为当您使用 GetKeyboardState API 函数时,您会得到最好的结果.

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

在 KeyDown 事件中,您只需询问键盘的状态".GetKeyboardState 将填充您提供的字节数组,该数组中的每个元素都代表键的状态.

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.

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

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).

有关详细信息,请参阅 MicrosoftGetKeyboardState 的文档.

For details see the Microsoft documentation for GetKeyboardState.

这篇关于在 C# 中捕获多个按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆