How to detect when a hotkey (shortcut key) is pressed

青春壹個敷衍的年華 提交于 2019-12-07 05:04:41

问题


How do I detect when a shortcut key such as Ctrl + O is pressed in a WPF (independently of any particular control)?

I tried capturing KeyDown but the KeyEventArgs doesn't tell me whether or not Control or Alt is down.


回答1:


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



回答2:


I finally figured out how to do this with Commands in XAML. Unfortunately if you want to use a custom command name (not one of the predefined commands like ApplicationCommands.Open) it is necessary to define it in the codebehind, something like this:

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

The XAML goes something like this...

<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>

And of course you need a handler:

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


来源:https://stackoverflow.com/questions/832185/how-to-detect-when-a-hotkey-shortcut-key-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!