捕捉在C#中的多个关键起伏 [英] Capture multiple key downs in C#

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

问题描述

我怎样才能捕捉多个关键起伏在C#中 Windows窗体工作形成时<? / p>

我好像不能同时获得这两个箭头,右箭头。


解决方案

我想你会是最好关闭时,您使用GetKeyboardState API函数。

 函数[DllImport(user32.dll中)]
公共静态外部INT GetKeyboardState(字节[] keystate);
私人无效Form1_KeyDown(对象发件人,发送KeyEventArgs E)
{
   字节[]键=新的字节[256];   GetKeyboardState(键);   如果((键[(INT)Keys.Up]放大器;键[(INT)Keys.Right]放大器; 128)== 128)
   {
       Console.WriteLine(向上箭头键和右箭头键了。);
   }
}

在KeyDown事件,你刚才问的键盘的国家。
该GetKeyboardState将填充你给字节数组,而这个数组再$ P $中的每个元素psents一个键的状态。

您可以通过使用每个虚拟键code的数值访问每个keystate。当该键的字节设置为129或128,这意味着该键一次(pressed)。如果该键的值是1或0,关键是向上(不是pressed)。值1是为切换键状态(例如,大写锁定状态)。

有关详细信息,请参阅href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms646299(v=vs.85).aspx\" rel=\"nofollow\">微软

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.

解决方案

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.

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

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