Playing with the toggle key LED’s

March 31, 2010

It’s actually pretty easy to programmatically turn the toggle keys on and off. By the toggle keys I mean the Num Lock, Caps Lock, and Scroll Lock keys at the corner of the keyboard.

I’m sure this has been done before but the information about how to do this was kind of difficult to find.

Using C, here’s a few routines that may be helpful:

#include <Windows.h>

struct KEY {
    char virtcode;
    char hardcode;
};

struct KEY NumLock =        {0x90, 0x45};
struct KEY ScrollLock =     {0x91, 0x46};
struct KEY CapsLock =       {0x14, 0x3a};

// Simulates a hardware key press.
// Input: Key we want to press.
void flipKey(struct KEY* key){

    // Simulate a key press and release.
    keybd_event(key->virtcode, key->hardcode, 0, 0);
    keybd_event(key->virtcode, key->hardcode, 2, 0);
}

// Returns the state of a key (on or off).
// 0 if off, 1 if on.
char getKey(struct KEY* key){
    return GetKeyState((BYTE) key->virtcode);
}

The method keybd_event requires both a virtual and a hardware code for a key. So for convenience, the two codes are grouped together into a struct.

So the code to flip Num Lock would be this:

flipKey(&NumLock);

This code infinitely loops a pattern on the three LED’s:

int main() {

    // Make sure all the keys are off.
    if(getKey(&NumLock)) flipKey(&NumLock);
    if(getKey(&CapsLock)) flipKey(&CapsLock);
    if(getKey(&ScrollLock)) flipKey(&ScrollLock);

    // Display a nice pattern.
    while(1){
        flipKey(&NumLock);
        Sleep(250);
        flipKey(&NumLock);

        flipKey(&CapsLock);
        Sleep(250);
        flipKey(&CapsLock);

        flipKey(&ScrollLock);
        Sleep(250);
        flipKey(&ScrollLock);

        flipKey(&CapsLock);
        Sleep(250);
        flipKey(&CapsLock);
    }

    return 0;
}

Maybe this will be of use to someone.


Follow

Get every new post delivered to your Inbox.

Join 63 other followers