Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Defining System-wide hotkeys in .NET

4.60/5 (8 votes)
30 Jun 2016CPOL2 min read 13.9K   543  
Using the Windows API to define systemwide hotkeys

Introduction

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)

Hotkeys.dll

Eums.cs contains Keys and Modifiers enumerations as provided in System.Windows.Input.

WinAPI.cs contains two methods needed for our usecase:

  • RegisterHotKey
  • UnregisterHotKey

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 HotKey namely 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 EventArgs containing:

  • definition of the pressed hotkey
  • the time it was pressed

HotKeyTest.dll

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.

C#
HotKeyListener.getInstance()
   .listenTo(HotKeys.ModifierKeys.Control | HotKeys.ModifierKeys.Shift, Keys.N, this.Hk_press);

Points of Interest

The HotKey class contains some code to ensure that the same handler can't subscribe twice for an event.

In the HotKeyListener class, I had to use ComponentDispatcher to have WPF play nicely with the WinAPI.

History

  • 30/06/2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)