具有 WPF KeyDown 事件的多个键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30941971/
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-09-13 13:13:03  来源:igfitidea点击:

Multiple keys with WPF KeyDown event

c#wpfkeyboardkeyboard-eventskeydown

提问by Dork

I'm working with WPF KeyDown event (KeyEventArgs from Windows.Input). I need to recognize when user pressed F1 alone and Ctrl+F1.

我正在处理 WPF KeyDown 事件(来自 Windows.Input 的 KeyEventArgs)。我需要识别用户何时单独按下 F1 和 Ctrl+F1。

   private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key==Key.F1 && Keyboard.IsKeyDown(Key.LeftCtrl))
        {
            MessageBox.Show("ctrlF1");
        }
        if (e.Key == Key.F1 && !Keyboard.IsKeyDown(Key.LeftCtrl))
        {
            MessageBox.Show("F1");
        }
    }

My problem is that when I press Ctrl+F1 plain F1 messagebox would fire too. I tried to add e.Handled to Ctrl+F1 case, but it doesn't help.

我的问题是,当我按 Ctrl+F1 时,普通的 F1 消息框也会触发。我尝试将 e.Handled 添加到 Ctrl+F1 大小写,但没有帮助。

回答by Michal_Drwal

Use:

用:

else if.....

In your case both options are fired, because you press the F1 key in both cases.

在您的情况下,两个选项都被触发,因为您在两种情况下都按下 F1 键。

回答by James Lucas

Use if and else otherwise all conditions get evaluated.

使用 if 和 else 否则所有条件都会被评估。

   private void Window_KeyDown(object sender, KeyEventArgs e)
   {
       if (e.Key==Key.F1 && Keyboard.IsKeyDown(Key.LeftCtrl))
       {
           MessageBox.Show("ctrlF1");
       }
       else if (e.Key == Key.F1 && !Keyboard.IsKeyDown(Key.LeftCtrl))
       {
           MessageBox.Show("F1");
       }
   }

回答by paparazzo

I think you are looking for Keyboard.Modifiers

我认为您正在寻找Keyboard.Modifiers

if ((Keyboard.Modifiers & ModifierKeys.Control) > 0)
{
    button1.Background = Brushes.Red;
}
else
{
    button1.Background = Brushes.Blue;
}

回答by ASh

check Key.F1 first, and if it pressed, then Key.LeftCtrl:

首先检查 Key.F1,如果按下,则 Key.LeftCtrl:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.F1)
    {
        MessageBox.Show(Keyboard.IsKeyDown(Key.LeftCtrl) ? "Ctrl-F1" : "F1");
    }
}