How to set leds in X, even on Ubuntu

#include <X11/Xlib.h>
#include <X11/XKBlib.h>

const int CapsLock = 2, NumLock = 16, ScrollLock = 1;

void setLeds(int leds) {
    Display *dpy = XOpenDisplay(0);
    XKeyboardControl values;
    values.led_mode = leds & ScrollLock ? LedModeOn : LedModeOff;
    values.led = 3;
    XChangeKeyboardControl(dpy, KBLedMode, &values);
    XkbLockModifiers(dpy, XkbUseCoreKbd, CapsLock | NumLock,
        leds & (CapsLock | NumLock) );

int main() {
    setLeds(CapsLock | NumLock | ScrollLock);

9 thoughts on “How to set leds in X, even on Ubuntu”

  1. This worked for me, but crashed after a while. I needed to add “XCloseDisplay(dpy)” at the end to avoid too many connections and a seg fault.

  2. Thanks for the comment Ed. I did fix that in our production app some months ago but forgot to update the blogpost :)

    1. Many thanks for your code. I’ve been wondering how to accomplish this feat. Now I have some free control lines to use so my keyboard emulator has I AND O. :-)

  3. At least on Ubuntu 12.04 (where the ledcontrol package has been deleted) you can also use xset (from the x11-xserver-utils package), e.g.

    xset led named “Scroll Lock”
    xset -led named “Scroll Lock”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s