WPF键盘快捷键 - 为什么这不起作用?

时间:2010-03-10 01:02:04

标签: c# wpf keyboard

我有以下代码(不起作用):

private void Window_PreviewKeyDown(object sender, KeyEventArgs e) {
    e.Handled = true;
    if ((e.Key == Key.P) && (Keyboard.Modifiers == ModifierKeys.Alt)) {
        MessageBox.Show("Thanks!");
    }            
}

为什么这不起作用?事件正在解雇,但

(e.Key == Key.P) && (Keyboard.Modifiers == ModifierKeys.Alt))

永远不会评估为真。 以这种方式使用 Ctrl 而不是 Alt 的类似事件起作用。此外,我的活动包括 Ctrl Alt

3 个答案:

答案 0 :(得分:3)

在WPF中使用密钥的更好方法是Key Gestures

e.g。 请注意,这是一个示例,而不是解决方案

<Window.InputBindings>
  <KeyBinding Command="ApplicationCommands.Open" Gesture="ALT+P" />
</Window.InputBindings>

还有更多内容,但你可以轻松地完成它。这是处理密钥的WPF方式!

PK: - )

答案 1 :(得分:2)

您需要使用ModifierKeys进行'按位和',如下所示...

    private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if ((e.Key == Key.P) && ((e.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt))
        {
            MessageBox.Show("Thanks!");
            e.Handled = true;
        }
    }

另外,不要忘记设置Handled参数的e属性...

答案 2 :(得分:0)

MSDN给了我们这个例子:

if(e.Key == Key.P && e.Modifiers == Keys.Alt)

这对你有用吗?

相关问题