This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 1.1+

Checking Lockable Key Statuses in .NET 1.1

The Scroll Lock, Caps Lock and Num Lock keys are three toggling keys on a standard keyboard. The status of each of these keys can affect a Windows application. However, when using the .NET framework 1.1, there is no simple way to obtain their status.

GetKeyState Function

In previous articles we have seen how to use the Console and Control classes to retrieve the status of the Caps Lock, Num Lock and Scroll Lock keys when using the .NET framework version 2.0. Unfortunately the classes in earlier versions of the framework do not provide a method or property that returns the status of these keys. Instead, you must use platform invocation services (P/Invoke) to execute the GetKeyState Windows API function. This requires the use of the System.Runtime.InteropServices namespace.

The GetKeyState function is found in the user32 library of the Windows API. It accepts a single parameter that specifies the virtual key for which you wish to find the status. Although not strictly necessary, it is customary to provide the key as a named constant as this makes the code more readable.

To import the DLL function for use by C# and to define the standard virtual key names, add the following declarations to your class. These define the API method that can be used to obtain the key status and key codes for the Caps Lock, Num Lock and Scroll Lock keys.

public static extern short GetKeyState(int keyCode);

int VK_CAPITAL = 0x14;
int VK_NUMLOCK = 0x90;
int VK_SCROLL = 0x91;

GetKeyState returns a sixteen-bit integer with two important bits. The high-order bit is set to one if the specified key is currently pressed. The low-order bit can be used to determine the toggle status of a lock key. If the low-order bit is one, the key is enabled. If it is zero, it is disabled.

The low-order bit is the important one for this article's purpose. To find its value, we can simply use the AND logical bitwise operator to isolate the bit and apply its value to a Boolean variable. In the code below, we check for the status of the scroll lock key.

bool scrollLock = Convert.ToBoolean(GetKeyState(VK_SCROLL) & 1);

Finally, we can test the status of the key with a simple if statement:

if (scrollLock)
    MessageBox.Show("Scroll Lock is on!");
22 January 2009