JNA:关键监听器+ JFrame

时间:2012-03-22 11:31:53

标签: java jna keylistener

我正在尝试编写一个简单的应用程序,我在后台和JFrame中有一个键盘监听器。实际上,我使用以下代码来创建侦听器:

public class KeyHook {
    private static volatile boolean quit;
    private static HHOOK hhk;
    private static LowLevelKeyboardProc keyboardHook;

    public static void main(String[] args) {
        final User32 lib = User32.INSTANCE;
        HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
        keyboardHook = new LowLevelKeyboardProc() {
            public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
                if (nCode >= 0) {
                    switch(wParam.intValue()) {
                    case WinUser.WM_KEYUP:
                    case WinUser.WM_KEYDOWN:
                    case WinUser.WM_SYSKEYUP:
                    case WinUser.WM_SYSKEYDOWN:
                        System.err.println("in callback, key=" + info.vkCode);
                        if (info.vkCode == 81) {
                            quit = true;
                        }
                    }
                }
                return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
            }
        };
        hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
        System.out.println("Keyboard hook installed, type anywhere, 'q' to quit");
        new Thread() {
            public void run() {
                while (!quit) {
                    try { Thread.sleep(10); } catch(Exception e) { }
                }
                System.err.println("unhook and exit");
                lib.UnhookWindowsHookEx(hhk);
                System.exit(0);
            }
        }.start();

        // This bit never returns from GetMessage
        int result;
        MSG msg = new MSG();
        while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
            if (result == -1) {
                System.err.println("error in get message");
                break;
            }
            else {
                System.err.println("got message");
                lib.TranslateMessage(msg);
                lib.DispatchMessage(msg);
            }
        }
        lib.UnhookWindowsHookEx(hhk);
    }
}

我的要求是首先创建侦听器,然后创建JFrame 。问题是由于GetMessage,我不知道如何创建JFrame。现在,GetMessage阻塞当前线程,因此我无法在其后创建JFrame。另一方面,我不能把它放在一个新的Thread中,因为那时,监听器不起作用。我希望你理解这个问题:)任何想法如何解决它?

提前致谢!

1 个答案:

答案 0 :(得分:1)

好的,这是解决问题的方法:

我们扔掉这个片段:

new Thread() {
   public void run() {
      while (!quit) {
         try { Thread.sleep(10); } catch(Exception e) { }
      }
      System.err.println("unhook and exit");
      lib.UnhookWindowsHookEx(hhk);
      System.exit(0);
   }
}.start();

接下来我们将main方法中的代码包含在:

new Thread(new Runnable() {
...
}).start();

然后,我们可以自由输入例如:

startListening(); // key listener

JFrame frame = new JFrame();
...
SwingUtilities.invokeLater(new Runnable() {

   @Override
      public void run() {
         frame.setVisible(true);
      }
});