如何在Linux上以编程方式打开/关闭Caps Lock,Scroll Lock,Num Lock键

时间:2016-08-11 11:08:45

标签: c++ keyboard opensuse capslock

是否有一种简单的方法可以使用C ++在Linux(OpenSuse)上打开/关闭Caps Lock,Scroll Lock和Num Lock,需要使用哪些头文件? 我想控制一些设备模拟击键。

1 个答案:

答案 0 :(得分:0)

解决方案1 ​​

请关注,因为此解决方案只需打开键盘的LED,如果您还需要启用大写锁定功能,请参阅解决方案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;
}

请记住,您必须以超级用户权限启动程序才能在文件/dev/console中写入。

修改

解决方案2

此解决方案适用于X11窗口系统管理器(在Linux上几乎是一个标准)。

// 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;
}

注意:可以在header 中找到更多的关键符号。