0

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

4

1 回答 1

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

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

于 2016-08-11T11:57:10.487 回答