Search code examples
c#.netwpfwindowshotkeys

How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?


I'm building an application in C# using WPF. How can I bind to some keys?

Also, how can I bind to the Windows key?


Solution

  • I'm not sure of what you mean by "global" here, but here it goes (I'm assuming you mean a command at the application level, for example, Save All that can be triggered from anywhere by Ctrl + Shift + S.)

    You find the global UIElement of your choice, for example, the top level window which is the parent of all the controls where you need this binding. Due to "bubbling" of WPF events, events at child elements will bubble all the way up to the root of the control tree.

    Now, first you need

    1. to bind the Key-Combo with a Command using an InputBinding like this
    2. you can then hookup the command to your handler (e.g. code that gets called by SaveAll) via a CommandBinding.

    For the Windows Key, you use the right Key enumerated member, Key.LWin or Key.RWin

    public WindowMain()
    {
       InitializeComponent();
    
       // Bind Key
       var ib = new InputBinding(
           MyAppCommands.SaveAll,
           new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control));
       this.InputBindings.Add(ib);
    
       // Bind handler
       var cb = new CommandBinding( MyAppCommands.SaveAll);
       cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing );
    
       this.CommandBindings.Add (cb );
    }
    
    private void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e)
    {
      // Do the Save All thing here.
    }