Setting up system-wide hotkeys

You can see examples of global system-wide hotkeys almost in every application: media players, chats, different tray tools. The application can be minimized or even hidden, but you can control it by pressing hotkeys no matter what is in focus right now.

Unfortunately, .NET Framework doesn't contain convenient classes or methods for setting up global system-wide hotkeys. The only way to achieve this is to use the Windows API functions.

To simplify registering, un-registering hotkeys in the system, and reacting on their pressings, I've created a small library GlobalHotKey. It provides an easy way to work with system-wide hotkeys by wrapping calls of native functions. Internally it uses Windows API RegisterHotKey and UnregisterHotKey functions and hides all interaction with them from you.

An example code how to use GlobalHotKey:

using System.Windows.Input;
using GlobalHotKey;

// ...

hotKeyManager = new HotKeyManager();
hotKeyManager.KeyPressed += HotKeyManagerPressed;

// ...

void HotKeyManagerPressed(object sender, KeyPressedEventArgs e)
{
    if (e.HotKey.Key == Key.F5)
    {
        MessageBox.Show("Hot key pressed!");
    }
}

// ...

// Register Ctrl+Alt+F5
var hotKey = hotKeyManager.Register(
    Key.F5, ModifierKeys.Control | ModifierKeys.Alt);

// Unregister Ctrl+Alt+F5
hotKeyManager.Unregister(hotKey);

// Dispose
hotKeyManager.Dispose();

Class HotKeyManager registers and unregisters system-wide hotkeys, handles them, and raises the event on hotkeys pressing. KeyPressedEventArgs class contains information about pressed hotkey and keys modifiers. Note also, that you don't need to unregister all hotkeys manually before disposing, because Dispose() does it internally.

The source code is available on GitHub.

On the Downloads page you can find already compiled assembly ready to use in your application. You can also install it in your application using NuGet:

Install-Package GlobalHotKey
previous post: P4Merge integration