Understanding multiple keys with WPF KeyDown event

963 views Asked by At

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

There are 1 answers

1
Flat Eric On BEST ANSWER

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