How can I turn on/off Caps Lock, Scroll Lock, Num Lock key programatically on Linux

回眸只為那壹抹淺笑 提交于 2019-12-25 06:12:24

问题


Is there a simple method to turn on/off Caps Lock, Scroll Lock and Num Lock on Linux (OpenSuse) using C++, what header files need to use? I want to control some device simulates keystrokes.


回答1:


Solution 1

Please go head because this solution just turn on the led of the keyboard, if you need to enable the caps lock funcion too, see solution 2.

// Linux header, no portable source
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
  int fd_console = open("/dev/console", O_WRONLY);
  if (fd_console == -1) {
    std::cerr << "Error opening console file descriptor\n";
    exit(-1);
  }

  // turn on caps lock
  ioctl(fd_console, 0x4B32, 0x04);

  // turn on num block 
  ioctl(fd_console, 0x4B32, 0x02);

  // turn off 
  ioctl(fd_console, 0x4B32, 0x0);

  close(fd_console);
  return 0;
}

Remember you have to launch your program with superuser privileges in order to write in the file /dev/console.


EDIT

Solution 2

This solution works with X11 window system manager (on linux is almost a standard).

// X11 library and testing extensions
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/XTest.h>

int main(int argc, char *argv[]) {
  // Get the root display.
  Display* display = XOpenDisplay(NULL);

  // Get the keycode for XK_Caps_Lock keysymbol
  unsigned int keycode = XKeysymToKeycode(display, XK_Caps_Lock);

  // Simulate Press
  XTestFakeKeyEvent(display, keycode, True, CurrentTime);
  XFlush(display);

  // Simulate Release
  XTestFakeKeyEvent(display, keycode, False, CurrentTime);
  XFlush(display);

  return 0;
}

Note: more key-symbol can be found in the header.



来源:https://stackoverflow.com/questions/38894697/how-can-i-turn-on-off-caps-lock-scroll-lock-num-lock-key-programatically-on-li

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!