title: sending fake keypress event to a window using xlib
body: <p>I'm trying to use C and xlib to send a fake keypress event to the window with focus, here's my code:</p>
  
  <pre><code>#include &lt;X11/Xlib.h&gt;
  #include &lt;X11/keysymdef.h&gt;
  #define XK_A            0x041
  
  int main()
  {
          Display *display = XOpenDisplay(NULL);
          //find out window with current focus:
          Window winfocus;
          int    revert;
          XGetInputFocus(display, &amp;winfocus, &amp;revert);
  
          //send key event to taht window
          KeySym sym;
          sym=XStringToKeysym("a");
          //event definition
          XKeyEvent event;
          event.type=KeyPress;
          event.keycode=XK_A;
          event.display=display;
          event.root=winfocus;
          XSendEvent(display,winfocus,True,KeyPressMask,(XEvent *)&amp;event);
  
          return 0;
  }
  </code></pre>
  
  <p>I'm trying to keep the code as simple as possible, I want to send the letter A to the active window
  I think I'm doing something wrong though</p>
  
  <p>thanks</p>
  
  <hr>
  
  <p>I tried the following code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;X11/Xlib.h&gt;
  #include &lt;X11/Xresource.h&gt;
  #include &lt;X11/Intrinsic.h&gt;
  #include &lt;X11/extensions/XTest.h&gt;
  #include &lt;unistd.h&gt;
  
  
  int main()
  {
          Display *dis;
          dis = XOpenDisplay(NULL);
          KeyCode modcode = 0; //init value
          modcode = XKeysymToKeycode(dis, XK_B);
          XTestFakeKeyEvent(dis, modcode, True, 0);
          XFlush(dis);
          sleep(1);
          XTestFakeKeyEvent(dis, modcode, False, 0);
          XFlush(dis);
          modcode = XKeysymToKeycode(dis, XK_A);
          XTestFakeKeyEvent(dis, modcode, True, 0);
          XFlush(dis);
  
  
  
  
          return 0;
  }
  </code></pre>
  
  <p>which presses the a key repeatedly, I'm unable to release that button if I dont use the sleep function, I'm unable to type the letter in once and then release the key press</p>