解决方案 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中找到。