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

5

如何在WPF中检测是否按下了快捷键,比如Ctrl+O(与任何特定控件无关)?

我尝试使用KeyDown来捕获,但KeyEventArgs没有告诉我是否已按下ControlAlt

2个回答

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

还有其他的方式可以注册快捷键吗,例如在XAML中? - Qwertie
2
看看这个帖子。https://dev59.com/KHRB5IYBdhLWcg3weHLx - JP Alioto

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
}

您也可以创建一个RoutedUICommand,并将特定的键盘手势与该命令关联起来,以避免在每个要实现此功能的窗口中放置KeyBinding代码。 - jpierson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接