I’m currently trying to create a little C/C++ program which emulates a key-press on one of the Multimedia-Keys (e.g. “Pause/Play”).
To simulate the keypress I used the XTestFakeKeyEvent-function from the X11-library’s. I found a working example here on SO: Simulate keypress in a Linux C console application
My problem is, that those special keys which I intend to simulate are not to be found in the keysymdef.h-file, where the constants for the used XKeysymToKeycode-function are defined.
So, I did a little research and found this post, which brought me to the xmodmap-command. Using xmodmap -pk I got a list which does include those keys:
KeyCode Keysym (Keysym) ...
Value Value (Name) ...
[...]
171 0x1008ff17 (XF86AudioNext) 0x0000 (NoSymbol) 0x1008ff17 (XF86AudioNext)
172 0x1008ff14 (XF86AudioPlay) 0x1008ff31 (XF86AudioPause) 0x1008ff14 (XF86AudioPlay) 0x1008ff31 (XF86AudioPause)
173 0x1008ff16 (XF86AudioPrev) 0x0000 (NoSymbol) 0x1008ff16 (XF86AudioPrev)
174 0x1008ff15 (XF86AudioStop) 0x1008ff2c (XF86Eject) 0x1008ff15 (XF86AudioStop) 0x1008ff2c (XF86Eject)
[...]
Using those defined values (like 172 for play/pause) as the keycodes for the XTestFakeKeyEvent-function I got it to work:
// Simulate Key-Press:
Display *display;
display = XOpenDisplay(NULL);
XTestFakeKeyEvent(display, 172, true, 0);
XTestFakeKeyEvent(display, 172, false, 0);
XFlush(display);
Now, my question is:
Can I rely on those values (the integers) to be mapped to these keys on every linux system? If not (which is what I guess), what would be the proper way to get the correct mappings dynamically (in code)?
I know this is not a definitive answer, but in my experience (with a similar project) the key mappings have been the same on every Linux machine I’ve tried it on. This has been only on machines with EN/US keyboard layout. I can’t speak about keyboards with alternative layouts.
I’m sorry if this does not answer your question completely.
EDIT:
I actually looked at my old project and it looks like I used these functions to get the actual keycodes:
Look at the MAN pages, they are pretty self explanatory.
I hope this helped 🙂