【问题标题】:How to detect when a hotkey (shortcut key) is pressed如何检测何时按下热键(快捷键)
【发布时间】:2010-10-24 08:22:31
【问题描述】:

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

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

【问题讨论】:

    标签: .net wpf keyboard-shortcuts hotkeys


    【解决方案1】:
    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
        {
            // CTRL is down.
        }
    }
    

    【讨论】:

    【解决方案2】:

    我终于想出了如何使用 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 代码放置在您可能希望在其中实现此功能的每个窗口中。
    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2019-03-10
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多