NHotkey is an open-source library for .NET that allows us to easily add custom keyboard shortcuts in Winforms or WPF applications.
These keyboard shortcuts are global, meaning they work even when your application does not have focus or is minimized. Adding global shortcuts is an interesting feature for our Apps.
For example, our program might minimize to the system tray, and we want it to show to the user when a key combination is pressed. Or to create a new note, or perform an action, whatever we want.
However, in general, setting up a hook for a keyboard shortcut to work globally, outside our application… well, the truth is, it’s a bit of a nightmare.
NHotkey is a library that makes this operation very simple, and it’s very useful for adding these “special features” to your application without having to die trying.
How to Use NHotkey
We can add the library to a .NET project easily, 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 your_command_name can be whatever you want and, it’s understood, you would have defined the function ‘your_callback_function’, with the name and code you want.
private void your_callback_function(object sender, HotkeyEventArgs e)
{
// whatever you want
}
That simple. No need to call the Windows API, no need 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

