Difference between revisions of "How to inject fake keystrokes"

From ThinkWiki
Jump to: navigation, search
 
m (formatting)
 
Line 1: Line 1:
 
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.
 
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 {{key|Esc}} key press (the keycode constant <tt>KEYCODE_ESC=9<tt> was found using <tt>xev</tt>):
+
Here is an example of such a program, which injects an {{key|Esc}} key press (the keycode constant <tt>KEYCODE_ESC = 9</tt> was found using <tt>xev</tt>):
  
 
<pre>
 
<pre>

Latest revision as of 09:34, 10 October 2006

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);
  XCloseDisplay(dpy);
  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.