Compact Framework: Global Hotkeys

13 April, 2010. It was a Tuesday.

A long time ago, in a galaxy far far away… well… back when I worked in VB.NET up in Dallas… I wrote a little hot key class for compact framework apps and posted a little bit on how to use it. Of course that was all done in VB.NET and I haven’t used that since the end of 2005. Fast forward 5 years and I find myself using the Compact Framework a lot and needing hotkeys again. So, here is the same code translated into C# (with the help of PInvoke.NET):

You’ll need to add a reference to Microsoft.WindowCE.Forms in your compact framework app.

The hot key interop call technically requires a windows form to receive the hotkey press using a windows message pump handler. This isn’t available in the standard System.Windows.Forms, but it is available in the MessageWindow class in the Microsoft.WindowsCE.Forms assembly. This code instantiates a class that inherits from MessageWindow so that we can handle the hot key press from anywhere in our application, not just from a specific form.

As an example of this being a global hotkey, create a Compact Framework app with a single form in it, and change your Program.cs to look like this:

1:staticclass Program

2: {

3:

4:privatestatic HotKeys hotKeys;

5:

6: [MTAThread]

7:staticvoid Main()

8: {

9: hotKeys = new HotKeys();

10: hotKeys.Register(Keys.A);

11: hotKeys.KeyPressed += hotKeys_KeyPressed;

12:

13: Application.Run(new Form1());

14: }

15:

16:privatestaticvoid hotKeys_KeyPressed(Keys key)

17: {

18:switch (key)

19: {

20:case Keys.A:

21: {

22: MessageBox.Show("You pressed A!");

23:break;

24: }

25:default: break;

26: }

27: }

28:

29: }

</div> </div>

Anytime you press the “a” or “A” key in the application, you’ll get a message box that pops up. The API for the HotKeys class could be made quite a bit more elegant, IMO. I don’t really like using switch statements like I showed in the program.cs… I would rather register a hotkey with a delegate that gets fired, like this:

1:privatevoid RegisterHotKeys()

2: {

3: hotKeys.Register(Keys.A, HandleAPress);

4: }

5:

6:privatevoid HandleAPress()

7: {

8: MessageBox.Show("You Presed A!");

9: }

</div> </div>

I don’t want to spoil all the fun of playing with this little snippet of code, though. So I’ll let you, the reader, explore the possibilities of implementing this API. 🙂