wpfglobalmodifiers

WPF Hotkey one key, no modifiers keys


can I made WPF application with one key hotkey? Everywhere is tutorial to make hotkeys with modifiers, like: [Alt]+[X]. For example I need made global hotkey [F9]. How can I do that in C# .NET 4.5 ?


Solution

  • Yes, you can. When you create your command object, one of the things you can pass is an InputGestureCollection, which contains a list of objects that descend from the InputGesture class. One of these classes is the KeyGesture class, which defines the specific key sequence used to use to activate the command.

    One of the properties of the KeyGesture class is the Key property, of type Key. This is an enumeration of key values. The one you want is Key.F9.

    To create the Command, you'd do something like this:

    InputGestureCollection myCommandGestures = new InputGesturecollection();
    myCommandGestures.Add( new KeyGesture( Key.F9 );
    RoutedCommand MyCommand = new RoutedCommand( "MyCommand", typeof( MyViewModelClass ), myCommandGestures );
    

    EDIT

    The above works within WPF only. If you want a global hot key, you'll have to call the Win32 RegisterHotKey function. The answer to this question on the Visual Studio forum contains a link to an example of how to do that.

    I'm not sure if you will have to do both or just call the RegisterHotKey function to register your hot key.