Multiple keys with WPF KeyDown event

僤鯓⒐⒋嵵緔 提交于 2021-02-19 04:16:06

问题


I'm working with WPF KeyDown event (KeyEventArgs from Windows.Input). I need to recognize when user pressed F1 alone and 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.


回答1:


Use:

else if.....

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




回答2:


Use if and else otherwise all conditions get evaluated.

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



回答3:


I think you are looking for Keyboard.Modifiers

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



回答4:


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

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


来源:https://stackoverflow.com/questions/30941971/multiple-keys-with-wpf-keydown-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!