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.
Asked
Active
Viewed 2,981 times
0
-
[This](http://stackoverflow.com/questions/2171408/how-to-change-caps-lock-status-without-key-press) question concerns Python, but is essentially the same, since the mechanism is, more or less, language-independent. I don't know if it's POSIX or supported by other Unices at all. – cadaniluk Aug 11 '16 at 11:11
1 Answers
0
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.
-
The super-user privilege thing sounds as silly as Windows often is. The opposite of security, when you have to allow anything in order to do some trivial but crucial little thing. Could it be possible to design a daemon process or something that could do this and provide an API to any non-privileged process? – Cheers and hth. - Alf Aug 11 '16 at 14:53
-
-
@MaysSpirit I think should be easier to find a solution for windows. Take a look on google, otherwise open a question on StackOverflow – BiagioF Aug 19 '16 at 10:08