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.