Manipulating Keyboard LEDs Through Software

© Amit Singh. All Rights Reserved.


Over the last few years, on my web sites ([1], [2]) and/or in my book, we have discussed how to access or manipulate several interesting components of Apple computers: the sudden motion sensor, the trusted platform module, the infrared remote control, the system management controller, traditional input devices, the backlit keyboard lights, the ambient light sensor, and so on. (Not all of these components are present on every Apple computer model.)

Undoubtedly, the most popular of these turned out to be the sudden motion sensor, which went on to be a building block for many, many cool programs.

Talking of LEDs and light, there still remain some lights on your computer that we haven't talked about. The caps lock and num lock LEDs on your keyboard—well, if your keyboard has these—are two of them. These LEDs can also be manipulated through software: you can both query and alter their state from your own program.

If you have an irrepressible urge to turn these LEDs on or off through software, here is a program that shows you how. (Note that the program only manipulates the LEDs—it will not actually cause caps lock or num lock to actually be engaged.) It's also an example of how to do user-space Human Interface Device (HID) programming through the I/O Kit.

The program should work whether you have a wired USB keyboard or a Bluetooth wireless keyboard. You would compile and run the program as follows.

$ gcc -Wall -o keyboard_leds keyboard_leds.c \ -framework IOKit -framework CoreFoundation $ ./keyboard_leds -h ... Usage: keyboard_leds [OPTIONS...], where OPTIONS is one of the following -c[1|0], --capslock[=1|=0] get or set (on=1, off=0) caps lock LED -h, --help print this help message and exit -n[1|0], --numlock[=1|=0] get or set (on=1, off=0) num lock LED ... $ ./keyboard_leds -c # query caps lock LED state off $ ./keyboard_leds -c1 # turn caps lock LED on off on $ ./keyboard_leds -c0 # turn caps lock LED off on off