You can see examples of global system-wide hot keys 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 hot keys no matter what is in focus right now.

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

To simplify registering, un-registering hot keys 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 hot keys 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);
// ...
hotKeyManager.Dispose();

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

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:

PM> Install-Package GlobalHotKey

Add comment