如何检测何时按下热键(快捷键)

时间:2009-05-06 22:48:39

标签: .net wpf keyboard-shortcuts hotkeys

如何在WPF中按下快捷键(例如 Ctrl + O )(独立于任何特定控件)?

我尝试捕获KeyDown,但KeyEventArgs并未告诉我 Control Alt 是否已关闭。

2 个答案:

答案 0 :(得分:10)

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
    {
        // CTRL is down.
    }
}

答案 1 :(得分:1)

我终于想出了如何使用XAML中的命令执行此操作。不幸的是,如果你想使用自定义命令名(不是像ApplicationCommands.Open这样的预定义命令之一),有必要在代码隐藏中定义它,如下所示:

namespace MyNamespace {
    public static class CustomCommands
    {
        public static RoutedCommand MyCommand = 
            new RoutedCommand("MyCommand", typeof(CustomCommands));
    }
}

XAML就是这样......

<Window x:Class="MyNamespace.DemoWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyNamespace"
    Title="..." Height="299" Width="454">
    <Window.InputBindings>
        <KeyBinding Gesture="Control+O" Command="local:CustomCommands.MyCommand"/>
    </Window.InputBindings>
    <Window.CommandBindings>
        <CommandBinding Command="local:CustomCommands.MyCommand" Executed="MyCommand_Executed"/>
    </Window.CommandBindings>
</Window>

当然,你需要一个处理程序:

private void MyCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
    // Handle the command. Optionally set e.Handled
}