Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

HotKey API.NET

0.00/5 (No votes)
17 Apr 2014 1  
Simple API to Register/Listen for HotKey in .NET applications

Introduction

Hi guys, it's gonna be quick since it's just a small contribution.

Here I developed a simple API that makes super easy to register/listen for hot-keys in any .NET application

When I first started with this component I faced myself with this question, "How do I do to set up a HotKey from a Class Library project?" because I'm aware that System.Windows.Forms has something to do about this, you can also listen for the keydown, but the application I was developing just had a From in order to input some configurations, after a "Play" button it was everything behind it. So investigating Pinvoke I saw that it was possible to register a HotKey via RegisterHotKey method, and also listen for WM_HOTKEY via SetWindowsHookEx.

After playing a while I started to abstract this on an independent solution that makes it super easy to treat with this issue.

I think that the way that someone can be benefited with this its because they simply have to attach this up, simply register any key combination and get to listen the event, ready to solve anything else that the consumer application's problem is. Making the Registration/Listening of HotKeys not one more issue to solve.

Background

You can also search for this in Nugget, the API is called HotKeysAPI.

Using the Code

//
// This is how you can create the specified hotKey
// 

var factory = new HotKeyFactory(); 
int keyCode = 77; //If I am not mistaken 77 is the keyCode for 'M'
var myHotKey = factory.CreateHotKey(keyCode)
              .WithControlPressed()
              .WithAltPressed()
              .GetHotKey();
//
// Well, registering into the SO its also very easy.
// 

var hotKeyRecorder = new HotKeyRecorder();
hotKeyRecorder.RegisterHotKey(myHoyKey);
//
// The only thing that's left is set up out ears to listen for that.
// 

var theListener = new HotKeyListener();
theListener.StartListening();
theListener.OnHotKeyPressed += MyHotKeyPressedEventHandler

The hotKey registration uses the RegisterHotKey API from user32. And the listening works via SetWindowsHookEx to the WM_HotKey window's message, after that the HotKey struct is reconstructed and notified to the Listener's instances via OnHotKeyPressed event.

This is not all the flexibility it has, but it is better if you check that yourself in the src. It's everything absolutly interfaced in case you need to unit test components with this.

Well guys, I hope you to find it as useful as I do. HF

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here