Qwertie
Qwertie

Reputation: 17186

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

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.

Upvotes: 5

Views: 4113

Answers (2)

Qwertie
Qwertie

Reputation: 17186

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
}

Upvotes: 1

JP Alioto
JP Alioto

Reputation: 45117

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

Upvotes: 11

Related Questions