Global keyboard and mouse hooks without the lag

September 20, 2007

 Note (10/6/2007): I found a much better (and simpler) way of doing this. Details below.

For the purposes of a project I was working on, I needed to detect when the user was pressing a key or moving the mouse. Because my project is all done in C#, I found this piece of code from Code Project very helpful. It’s just a drop-in class that notifies you whenever you receive a keystroke or mouse activity. All was great except for one thing: when you click on the minimize, maximize, or close buttons of your application, the whole application starts stuttering. Other applications running at the time are not affected, but this little problem plagues every implementation of global mouse hooks that I could find, whether written in managed or unmanaged code. Instead, I’m going to use a more roundabout method. I’ll have a very small Win32 app print basic information about events to the console, and then read this information in from my C# application. I found this great little C++ global hooking app after a lot of looking.

Addendum (10/6/2007):

It turns out  a much simpler way is to set up the hook in a new thread. You simply create a new thread and call SetWindowsHookEx from that thread. However, if that is all you do you will not be receiving any events. You need to create a message loop in the thread that reads messages coming to it and processes them. Fortunately, this is very easy. Using WPF, all you need to do is call Dispatcher.Run() after you initialize the hook. Using Windows Forms, I think all you need to do is call Application.Run().

Leave a comment