在 C# 中捕获多个按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/709540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 14:18:19  来源:igfitidea点击:

Capture multiple key downs in C#

c#winforms

提问by Presidenten

How can I capture multiple key downs in C# when working in a Windows Formsform?

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

I just can't seem to get both the up arrow and right arrow at the same time.

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

采纳答案by Frederik Gheysels

I think you'll be best off when you use the GetKeyboardState API function.

我认为您最好使用 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.");
   }
}

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.

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

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

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

For details see the Microsoft documentation for GetKeyboardState.

有关详细信息,请参阅GetKeyboardStateMicrosoft 文档

回答by RvdK

Hmm, are there separate events for each key down?

嗯,每个按键都有单独的事件吗?

You can create four booleans for each arrow. When it is pressed, set the boolean of that arrow to true. If released is fired, set the boolean of that arrow to false.

您可以为每个箭头创建四个布尔值。当它被按下时,将该箭头的布尔值设置为 true。如果被释放,则将该箭头的布尔值设置为 false。

Then you can check if the up and right boolean are true and then do your action.

然后您可以检查 up 和 right 布尔值是否为真,然后执行您的操作。

回答by Tormod Fjeldsk?r

A little proof-of-concept code for you, assuming Form1contains label1:

为您提供一些概念验证代码,假设Form1包含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;
    }
}

回答by HasaniH

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.

使用 SPY++ 查看按键是如何触发的。基本上,如果同时按住多个箭头键,第一个被击中的键将触发事件,然后当第二个键被击中时,它将开始触发,您将不​​再看到第一个键的事件。当他们被释放时,你会看到他们的关键事件。我建议你实现之前建议的 bool 标志,它快速而简单。

回答by Andreas

With

Keyboard.IsKeyDown(Key.YourKey) 

you can handle multiple keydowns.

您可以处理多个按键。

回答by George Mamaladze

There is a managed library MouseKeyHook as NuGetwhich gives you a convenience managed wrapper. Source code on GitHub.

有一个托管库MouseKeyHook 作为 NuGet,它为您提供了一个方便的托管包装器。GitHub 上的源代码

Recently support for detecting shortcuts, key combinations and sequences was added. Here is a usage example to deal with arrows:

最近添加了对检测快捷方式、组合键和序列的支持。这是一个处理箭头的用法示例:

Hook.AppEvents().OnCombination(new Dictionary<Combination, Action>
{
    {Combination.FromString("Left"), GoWest},
    {Combination.FromString("Left+Up"), GoNorthWest},
    {Combination.FromString("Up+Left"), GoNorthWest},
    {Combination.FromString("Up"), GoNorth},
    {Combination.FromString("Up+Right"), GoNorthEast},
    {Combination.FromString("Right+Up"), GoNorthEast},
});

For more information see: Detecting Key Combinations and Sequences

有关更多信息,请参阅:检测键组合和序列