title: Why can't I capture these KeyPress / KeyRelease events from inside my loop?
body: <p>I want to record all incoming keypress events, no matter which window is in focus or where the pointer is.  I have written sample code which should capture the key pressed events of the current window in focus (see below).  To keep my code readable, I have given the sample code only for the window in focus.  As my final aim is to capture key press events on the screen irrespective of the Window in focus, I plan to use <code>XQueryTree</code> to get all the Windows and apply the same logic.</p>
  
  <p>I am calling <code>XGrabKeyboard</code> to capture the keyboard, as the window in focus might already be grabbing the keyboard events.  With my sample code, I am able to grab the keyboard, but cannot receive <code>KeyPress</code> or <code>KeyRelease</code> events for any keyboard keys inside the <code>while</code> loop.</p>
  
  <p>What am I missing in the code to allow me to receive the events?</p>
  
  <p>Sample Code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;locale.h&gt;
  #include &lt;stdint.h&gt;
  #include &lt;stdarg.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;X11/Xlib.h&gt;
  #include &lt;X11/Xos.h&gt;
  #include &lt;X11/Xfuncs.h&gt;
  #include &lt;X11/Xutil.h&gt;
  
  #include &lt;X11/Xatom.h&gt;
  int _invalid_window_handler(Display *dsp, XErrorEvent *err) {
      return 0;
  }
  
  int main() 
  {
      Display *display = XOpenDisplay(NULL); 
      int iError;
      KeySym k;
      int revert_to;
      Window window;
      XEvent event;
      Time time;
      XSetErrorHandler(_invalid_window_handler);
      XGetInputFocus(display, &amp;window, &amp;revert_to);
      XSelectInput(display, window, KeyPressMask | KeyReleaseMask );
      iError = XGrabKeyboard(display, window,
                            KeyPressMask | KeyReleaseMask,
                            GrabModeAsync,
                            GrabModeAsync,
                            CurrentTime); 
      if (iError != GrabSuccess &amp;&amp; iError == AlreadyGrabbed) {
          XUngrabPointer(display, CurrentTime);
          XFlush(display);
          printf("Already Grabbed\n");    
      } else if (iError == GrabSuccess) {
          printf("Grabbed\n");
      }
      while(1) {
            XNextEvent(display,&amp;event);
            switch (event.type) {
                case KeyPress : printf("Key Pressed\n"); break;
                case KeyRelease : printf("Key Released\n"); break;
                case EnterNotify : printf("Enter\n"); break;
            }
      }
      XCloseDisplay(display);
      return 0;
  }
  </code></pre>