How to inject fake keystrokes

From ThinkWiki
Revision as of 09:34, 10 October 2006 by Thinker (Talk | contribs) (formatting)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Some special keys do not create keyboard events, but can be monitored by the tpb and KMilo programs. The latter can execute arbitrary commands. If you want to create a fake keystroke corresponding to the special key, you need to execute a command that generates a synthetic keyboard event.

Here is an example of such a program, which injects an Esc key press (the keycode constant KEYCODE_ESC = 9 was found using xev):

#include <X11/extensions/XTest.h>

#define KEY_DOWN True
#define KEY_UP   False

#define KEYCODE_ESC 9

int main() {
  Display *dpy = XOpenDisplay(NULL);
  if (!dpy) return 1;
  XTestFakeKeyEvent(dpy, KEYCODE_ESC, KEY_DOWN, CurrentTime);
  XTestFakeKeyEvent(dpy, KEYCODE_ESC, KEY_UP, CurrentTime);
  return 0;

Save this as injectkey.c and compile using

$ gcc -o injectkey -lXtst injectkey.c

Then configure tpb or KMilo to invoke it, e.g., for the FnSpace ("Zoom") event.