title: "global" KeyListener using JNA
body: <p>I have in plan making of program in Java running under Windows that can map diffenrent "macros" on different keys runnig at background. Problem is - how to make Java listen to keys pressed when the application is not being focused.  </p>
  
  <p>I have found lot of opinions that this is not possible. But I have also found <a href="https://stackoverflow.com/questions/696170/java-keylistener-without-window-being-open/4394398#4394398">this</a> written by Stefano here on SO. This solution is, well, not good enough for me, at least there is not one impotant information. The function <code>MsgWaitForMultipleObjects()</code> returns one value if the key is not pressed...that's ok. After key press, it returns different value...that would be ok, if the function wouldn't return the same value whatever happens after the key press event.  </p>
  
  <p>Here is the thread testing this:</p>
  
  <pre><code>public class KeyListener extends Thread {
  
      /**
       * Constructor
       */
      public KeyListener() {
          super();
      }
  
      /**
       * RUN method
       */
      @Override
      public void run() {
          int x;
          User32 user32 = User32.INSTANCE;
  
          boolean res = user32.RegisterHotKey(Pointer.NULL, 1, User32.MOD_ALT | User32.MOD_CONTROL, WinKeys.VK_X);
          if (!res) {
              System.out.println("Couldn't register hotkey");
          }
          System.out.println("Starting and waiting");
  
          while (!isInterrupted()) {
              x = user32.MsgWaitForMultipleObjects(0, Pointer.NULL, true, 1000, User32.QS_HOTKEY);
  
              if (x == 0) {
                  System.out.println("Key pressed");
              }
          }
      }
  }
  </code></pre>
  
  <p>This little program (using this thread) reacts on pressing <code>ALT+X</code>. After this is pressed, the text <code>Key pressed</code> is written out to the console until the program stops (the function returns 0 all the time). Possible solution is in my opinion some "reset" of the function so it will wait for the key press again and return <code>258</code> again (<code>258</code> == waiting). But I have no idea how to do this.  </p>
  
  <p>If somebody knows, how to do this, or is there is another solution, I would be grateful for any information.</p>