When I created an application which needed to be notified whenever a combination of keys is pressed, I noticed there is no standard solution provided for this usecase.
My goal was to write a library that allowed to define hotkeys and send notifications to the subscribed objects even when the application has no focus, is minimized, etc.
I simplified my library to demonstrate a possible approach.
Using the Code
The project is composed of two assemblies:
- Hotkeys.dll (class library)
- HotKeyTest.exe (WPF test project)
Eums.cs contains Keys and Modifiers enumerations as provided in
WinAPI.cs contains two methods needed for our usecase:
HotkeyListener.cs encapsulates the interaction with the
WinAPI to provide a facade between the
WinAPI and the code consuming the
HotKeys library code.
HotKey.cs encapsulates the definition of a
Modifiers (4bits) and
Key. Each unique combination gets a unique ID, calculated as follows: cast both
enums to integers, shift the
Key number with 4 positions (modifiers are composed out of 4 bits) and add the resulting integers.
HotKeyEventArgs is a specialisation of
- definition of the pressed
- the time it was pressed
Contains a simple WPF application for testing purposes.
Control + Shift + N is defined by default, by clicking the button, you can add Control + K as a shortcut.
Using the library is as simple as getting an instance of the
HotKeyListener class through the singleton pattern + supply the
hotkeys you are interested in.
.listenTo(HotKeys.ModifierKeys.Control | HotKeys.ModifierKeys.Shift, Keys.N, this.Hk_press);
Points of Interest
HotKey class contains some code to ensure that the same handler can't subscribe twice for an event.
HotKeyListener class, I had to use
ComponentDispatcher to have WPF play nicely with the
- 30/06/2016: Initial version