Suppose that, for some reason, you’d like to have a program that sends a key combination such as <Control+Left Arrow> to your X server. You can do that trivially using the X Test extension and XTestFakeKeyEvent, but if you want something a bit more flexible you can add a configuration file like
fwd 64 102 back 64 100
where the command back would simulate simultaneous keypresses of ALT (keycode 64) and Left Arrow (keycode 100). Don’t ask why would someone want to do something like this — the only thing I can assure you is that we had a good reason. If that’s your case, the following C program is what you need. Released to the public domain, compile and link against libXtst.
Update: a better version is available.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/extensions/XTest.h>
#define CONFFILE "conf"
#define LINE_MAX 256
#define KEY_MAX 10
int main(int argc, char **argv)
{
FILE *f;
char *token = NULL, line[LINE_MAX];
int key[KEY_MAX];
Display *dpy;
int i, keynum;
if (argc != 2)
fprintf(stderr, “usage: %s <command>\\n”, argv[0]), exit(1);
if ((f = fopen(CONFFILE, “r”)) == NULL)
fprintf(stderr, “can’t find configuration file\\n”), exit(1);
for (; !feof(f); token = NULL) {
fgets(line, LINE_MAX, f);
token = strtok(line, ” \\t”);
if (!strcmp(argv[1], token))
break;
}
fclose(f);
if (!token)
fprintf(stderr, “command %s not defined\\n”, argv[1]), exit(1);
for (i = 0; i < KEY_MAX; i++) {
if ((token = strtok(NULL, " \\t")) == NULL)
break;
key[i] = strtoul(token, NULL, 0);
}
keynum = i;
if ((dpy = XOpenDisplay(NULL)) == NULL)
fprintf(stderr, "can't open display\\n"), exit(1);
for (i = 0; i < keynum; i++)
XTestFakeKeyEvent(dpy, key[i], True, CurrentTime);
while (i--)
XTestFakeKeyEvent(dpy, key[i], False, CurrentTime);
XCloseDisplay(dpy);
return 0;
}
Entries (RSS)
August 29th, 2007 at 1:12 pm
You could also make a link so we can download the attachment instead of copying & pasting the whole code. Think about future Wordpress breakages and your previous post :-D
August 29th, 2007 at 1:26 pm
Nah, I’m too lazy for that. You can do it ;)
August 29th, 2007 at 1:38 pm
But ok, I confess, the main reason to leave it inline instead of adding a link is that in the latter case I’d have to give a name to the program, and true hacks are always called a.c/a.out. I could call this a.c and the next would be b.c, but it would become too elaborate a scheme. Better leave it inline.
September 6th, 2007 at 1:39 pm
[...] Boiko gave it a name so I threw in a couple of additional lines to justify the name change. Unlike your [...]