Tuesday, September 1, 2009

Toggle Keys Controller


A couple of days before I wrote this article, a member asked how to control the Caps, Num and Scroll lock keys. I knew there were several implementations around so I searched with a view to providing the poster with a link, but I couldn't find one that was complete. Many just read the state of these keys, some also allowed you to set them, but I couldn't find any that monitored them so your application was updated accordingly. So, this article is the result. The ToggleKeysController class in the code attached will monitor these keys and raise events when a change is detected, and allow you to get or set the state.

Unanticipated Problems

This isn't quite as simple as I first thought it would be! The first thing to do was to get the state of the keys. I knew the Console class had a CapsLock property so I figured it would probably be the answer. Unfortunately, it doesn't have a ScrollLock property.

The next step was to set the key states. The ones that are in the Console class are read only, so now that class was definitely out of the question. I had a look at SendKeys for this, but that doesn't allow you to permanently change the state as demonstrated here.

Finally, I wanted to be able to monitor the state of these keys system wide so the information I was providing was always up to date. I couldn't find a way to do this either using classes in the framework, so not a good start.

The answer to all these problems was a little bit of PInvoke into user32.dll (and kernel32.dll) which has all the native functions we need.

Getting the Key States

Getting the state of a key requires a call to the GetKeyState function. This function simply takes a value that represents a key, and returns a value indicating its state. This example shows just how easy it is to use to get the state of the CapsLock key.

See full detail: http://www.codeproject.com/KB/miscctrl/togglekeyscontroller.aspx

No comments: