使用WPF KeyDown事件了解多个键 [英] Understanding multiple keys with WPF KeyDown event

查看:155
本文介绍了使用WPF KeyDown事件了解多个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WPF KeyDown事件.当我按 Ctrl + F1 时,您能否解释为什么这种情况成立?当我按下 F1 时,已经按下了 Ctrl ,因此!Keyboard.IsKeyDown(Key.LeftCtrl)应该为false.

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.

在下面的代码中,如果按 Ctrl + F1 ,则会同时触发两条消息.但是,如果您更改这两个if语句的顺序,则只会触发"ctrlF1"消息.我想解释一下这种奇怪的行为.

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

推荐答案

区别如下:

  • 在显示的代码中,进入处理程序时,按下 F1 并按下 Ctrl (两个if子句都为真的条件). MessageBox阻止线程.同时,释放 Ctrl 键,然后单击消息.然后代码执行继续,并且不再按下 Ctrl 键(第二个if子句的条件均成立)
  • 如果切换if语句,则只有第一个if语句的第一个条件(e.Key == Key.F1)为true.执行到第二个if语句,并且两个条件都成立.显示MessageBox并停止执行,直到关闭MessageBox.
  • 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.

区别在于:在调用处理程序之前先评估按下 F1 键,但是在执行代码行的那一刻评估检查Keyboard.IsKeyDown(Key.LeftCtrl)

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

这篇关于使用WPF KeyDown事件了解多个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆