5

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

我尝试捕获KeyDown,但并没有KeyEventArgs告诉我是否关闭。ControlAlt

4

2 回答 2

11
private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
    {
        // CTRL is down.
    }
}
于 2009-05-06T23:10:19.200 回答
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
}
于 2009-05-07T17:10:19.430 回答