问题
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