Wednesday, July 09, 2008

Locking Keyboard and Screen on Windows Mobile

There was a question in the community today regarding locking the keyboard and screen. I thought this was a good question so decided to write an article about how to do it.

There is a very simple solution to this problem so long as the device supports locking the device, which is on most WM5 and later devices. This code should work on CE devices also. Simply P/Invoke the keybd_event procedure passing hex 0x85.

For a list of key codes see here:

So I have knocked up a very simple application with one button which locks the device:

Click to show a larger image

When we click the Lock button you'll notice the menubar soft input 1 changes to read Unlock and the device is completely inaccessible, tapping even the start menu will not work apart from soft input 1:

Click to show a larger image

Clicking Unlock shows this screen:

Click to show a larger image

Of course clicking Unlock in the middle of the screen returns to you're app.

This approach can be used for many different features, check out the list of codes above. A simple way of achieving many features of the device.

The code looks like the following:
[DllImport("coredll.dll", EntryPoint = "keybd_event", SetLastError = true)]
internal static extern void keybd_event(byte bVk, byte bScan,
int dwFlags, int dwExtraInfo);

private void lockDevice_Click(object sender, EventArgs e)
keybd_event(0x85, 0,0,0);


Anonymous said...

Thank you very much - exactly what I was looking for days now :)

Anonymous said...


thank you for your code and explanation. Do you know a way to capture all Key-Events (especially the Screen-Unlock-Event)? I tryed with

SetWindowsHookEx(WH_KEYBOARD_LL, hookDeleg, GetModuleHandle(null), 0);

I reveice the events sent from my application, but can not capture the event of unlocking the screen.

Thanks in advance