Hooking to keyboard in Windows Mobile
Tuesday, September 30th, 2008Let’s say you built an application that need to know when certain keyboard buttons are pressed. Let’s say you need to get such events even while running the application in the background and some other application is running in the foreground. Well, there’s an easy to use native API that does that: SetWindowsHookEx. There’s an excellent by Alex Yakhnin on how to use and integrate the method to managed application.
However, before using the method, you should consider the following. The method is a private API. Meaning, it can change or even remove in the next CE version. More over, OEMs can decide to remove it themselves. The result is that you have angry customers complaining about your application and you have no idea why. For more information, check this post from Raffael Limosani of Microsoft CSS (Customer service and support). BTW, I highly recommends reading Raffael’s posts. They are very informative and to the point.
So, you read the disclaimers and decide to continue and use the method. Alex’s code is excellent but there’re couple of points you need to consider. First of all, each button press initiates at least two events for the button. The first is for the state where the key is pressed (down). The other is of course, when the button is released (up). I decided to handle the down event in order to catch the event before other applications.
That brings up to the second point. Other programs are also hooking. Usually, you don’t mind. Every time the hook procedure you set in SetWindowsHookEx is called, you do your stuff. When finished, pass the event to the next hook by calling the appropriately named method CallNextHookEx and return its result. However, if you wish to prevent the key event to pass to other hook, then don’t call CallNextHookEx. Instead, just return 0. Blocking other programs from these events is not very friendly behavior so thing carefully before doing it.
On some cases, avoiding the call to CallNextHookEx might not be enough though. For example, the green (send) and red (end) buttons. It seems that the phone application catches events when these buttons are pressed even if you don’t call CallNextHookEx. If you wish to block that as well, have your hook procedure return -1. If you do return 0, expect the phone application to send another key up event upon completion of event processing. Don’t take my word for it. Try it for your self.
Finally, don’t forget to call UnhookWindowsHookEx before closing your application or you’ll get a nasty error about WinCe5011bException.