Friday, February 20, 2009

RegisterHotKey in C#

I like .Net framework for its huge class library covering almost anything you'll ever need. One thing I could not find was registering a windows hot-key in C#. It seems the framework does not provide a solution for system-wide hot keys. So I had to use the good old RegisterHotKey Win32 function.

To call it from C#, you need to use P/Invoke service to invoke the unmanaged function residing in user32.dll

using System.Runtime.InteropServices;

private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

The hWnd parameter is the handle of a form that will receive WM_HOTKEY message. To get the handle of a Form simply use Handle property. In order to process WM_HOTKEY message, your form needs to override WndProc method.

Just one more thing you should know: RegisterHotKey and ShowInTaskBar property don't mix well. It seems that a new window is created each time ShowInTaskBar property is called so your WndProc mehod will stop recieving hot-keys. You need to RegisterHotKey again because Handle property returns a new window handle after ShowInTaskBar was called.

No comments: