GetKeyboardState() & MouseHooks – Not available in Windows Mobile

I was writing a small piece of code for Windows Mobile in C# and wanted to use GetKeyboardState() but after a lot of searching around found out that the API is not available. Also Mouse Hooks does not work in Windows Mobile. As simple as this information seems, it took me a lot of time to search and basically validate that information. Of course the various ideas and blog posts out there are pretty confusing and does not allow you to reach to a conclusion easily.

You can find the associated code in C# at The code is without any cleanups now but expect a better cleaned up and documented version later on.

To give a brief:

– Extract the files in your project directory.

– In the code where you need to install and capture key events, include a private variable GlobalHooks like shown below:

private GlobalHooks globalHooks = new GlobalHooks(Process.GetCurrentProcess().MainWindowHandle);

– After initializing your other components either in the class constructor or other methods, register for the events that you would like to handle as shown below:


            // Register EventHandlers
            globalHooks.KeyDown += new KeyEventHandler(globalHooks_KeyDown);
            globalHooks.KeyPress += new KeyPressEventHandler(globalHooks_KeyPress);

– Then write the associated event handler. In the following example, I have registered for KeyDown events and am suppressing the hard key LSK events.

        void globalHooks_KeyDown(object sender, KeyEventArgs e)
            Debug.Write(String.Format("KeyDown: Control: {0}, Alt: {1}, Shift: {2}, KeyCode: {3}\n", e.Control, e.Alt, e.Shift, e.KeyCode));
            if (e.KeyCode == Keys.LWin || e.KeyCode == Keys.Apps)
                e.Handled = true;

– No need to mention that you need to use globalHooks.RemoveHooks() once you are done with your application, else you need a reboot !

So there you go. Enjoy and give me feedback on the forum.