Thursday, February 26, 2009

Testing for a Toggled Key

There are several keys on the keyboard that can be in a toggled state: num lock, scroll lock, cap lock and insert. There is a convenient method in the Control class that will get the state of the button: Control.IsKeyLocked(key). The key parameter can be one of Keys.CapLock, Keys.NumLock, Keys.Scroll and Keys.Insert. The method returns true if the key is in the toggled state, otherwise it returns false.

According to the MSDN documentation, the method will throw a NotSupportedException if the key is not CapLock, NumLock or Scroll; however, Insert also works and does not throw an exception.

This method has been available since .NET 2.0. For earlier versions, it was necessary to do some interop with the user32.dll. There is a method that returns a bit field for the state of a key. For keys that can be toggled, the lowest bit in the field will be 1. Use a bitwise & operation to isolate the bit.

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern ushort GetKeyState(int keyCode);

//From winuser.h
private const int VK_INSERT = 0x2D;
private const int VK_NUMLOCK = 0x90;
private const int VK_SCROLL = 0x91;
private const int VK_CAPITAL = 0x14;

public static bool IsKeyToggled(int nKey)
{
return (GetKeyState(nKey) & 0x01) == 1;
}

The hex codes for the keys can be obtained from winuser.h. In VS08, I found this file under the SDK folder for smart phones and pocket PC.

For Vista, there is also a Keyboad class that is part of the System.Windows.Input namespace. References to the presentation core and to the windows base dll's must be made. The presentation core contains the Keyboard and Keystate classes. The windows base contains the Key class. Be careful with the Key class, since there is also a Key class in System.Windows.Forms.

Keyboard.GetKeyStates(Key.CapsLock) == KeyStates.Toggled

 

No comments:

Post a Comment

Followers