views:

727

answers:

2

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.

+4  A: 
private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
    {
        // CTRL is down.
    }
}
JP Alioto
Are there any other ways to register shortcut keys, e.g. in XAML?
Qwertie
Check this thread out. http://stackoverflow.com/questions/612966/keyboard-events-in-a-wpf-mvvm-application
JP Alioto
A: 

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