Understanding multiple keys with WPF KeyDown event

谁都会走 提交于 2021-01-28 18:08:51

问题


I'm using WPF KeyDown event. Can you please explain why this condition is true, when I press Ctrl+F1? When I press F1, Ctrl is already pressed so !Keyboard.IsKeyDown(Key.LeftCtrl) should be false.

Edit:

In the code below if you press Ctrl+F1 both messages would fire. But if you change the order of these two if statements, only "ctrlF1" message would fire like it should be. I would like to get explanation of that strange behavior.

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

回答1:


The difference is as follows:

  • In the code you showed, when entering the handler, F1 is pressed and Ctrl is pressed (both conditions of first if-clause are true). MessageBox blocks the thread. Meanwhile you release the Ctrl key and click at the message. Then code execution goes on and Ctrl key is no longer pressed (both conditions of the second if-clause are true)
  • If you switch the if-statements, only the first condition (e.Key == Key.F1) of the first if-statement is true. Execution comes to second if-statement and both conditions are true. MessageBox is shown and execution stops till the MessageBox is closed.

The difference is: Pressing of the F1 key is evaluated before the handler is called, but the check Keyboard.IsKeyDown(Key.LeftCtrl) is evaluated in the moment, when the line of code is executed



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

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