Multiple keys with WPF KeyDown event

11.6k views Asked by At

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.

4

There are 4 answers

0
Michal_Drwal On BEST ANSWER

Use:

else if.....

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

1
James Lucas On

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

I think you are looking for Keyboard.Modifiers

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

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