Unicode keyboard input faking



I've just discovered that there's a remarkably well undocumented feature
in the XStringToKeysym functionality in XFree 4.0.2 and later. 
Attempting to convert a string in the form U0041 will generate a keysym
from a specific range, and keycodes can have this allocated to them. The
following code will accept a Unicode character of this form as its first
argument, do stupid nasty things to the keymap and then fake a key
event. Ought to work for any Unicode character that's supported by your
locale. Needs to be linked against Xtst as well as X11. The (insanely
scant) documentation I've found suggests that testing for
X_HAVE_UTF8_STRING being defined will tell you if this functionality
exists or not.

-- 
Matthew Garrett | mjg59 srcf ucam org
#include <stdio.h>
#include <X11/X.h>
#include <X11/Xlib.h>

int main(int argc, char* argv[]) {
  Display *dpy;
  dpy = XOpenDisplay(NULL);

  if (argc!=2) {
    printf("This program takes a single keysym name (such as A or U0041) as an argument\n");
    return 1;
  }

  KeySym sym = XStringToKeysym(argv[1]);

  int min, max, numcodes;
  XDisplayKeycodes(dpy,&min,&max);
  KeySym *keysym;
  keysym = XGetKeyboardMapping(dpy,min,max-min+1,&numcodes);
  keysym[(max-min-1)*numcodes]=sym;
  XChangeKeyboardMapping(dpy,min,numcodes,keysym,(max-min));
  XFree(keysym);
  XFlush( dpy );

  KeyCode code = XKeysymToKeycode(dpy,sym);

  XTestFakeKeyEvent(dpy, code, True, 1);
  XTestFakeKeyEvent(dpy, code, False, 1);

  XFlush( dpy );

  XCloseDisplay( dpy );

  return 0;
}










[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]