Language: EN

nhotkey

How to create keyboard shortcuts in C# with NHotkey

NHotkey is an open-source .NET library that allows us to easily add custom keyboard shortcuts in Winforms or WPF applications.

These keyboard shortcuts are global, meaning they work even if your application does not have focus or is minimized. Adding global keyboards is an interesting functionality for our apps.

For example, our program may be minimized to the system tray, and we may want it to be displayed to the user when a keyboard combination is pressed. Or to create a new note, or perform an action, whatever we want.

However, in general, defining a hook for the keyboard shortcut to work globally, outside of our application… well, it’s a bit of a nightmare.

NHotkey is a library that makes this operation very easy, and it is very useful for adding these “special features” to your application without having to die trying.

How to use NHotkey

We can easily add the library to a .NET project through the corresponding NuGet package.

Install-Package NHotkey.Wpf

Next, defining a keyboard shortcut is as simple as,

HotkeyManager.Current.AddOrReplace("your_command_name", Keys.Control | Keys.Alt | Keys.Add, your_callback_function);

The name_of_your_command can be whatever you want, and it is understood that you would have defined the ‘your_callback_function’ function, with the name and code you want.

private void your_callback_function(object sender, HotkeyEventArgs e)
{
    // whatever you want
}

That simple. Without having to call the Windows API, without having to deal with DLLs, or absolutely anything. One line of code, and it works.

NHotkey is Open Source, and all the code and documentation is available in the project repository at https://github.com/thomaslevesque/NHotkey