React on Global Hotkey in a Java Program on Windows/Linux/Mac

global KeyListener using JNA

I don't know about JNA solution, but there is a well-established global hotkey library called JIntelliType

EDIT: Correct answer to this problem was to use GetMessage instead of MsgWaitForMultipleObjects. I wrote a simple example using BridJ and it works great:

       if (!RegisterHotKey(null, id, MOD_ALT | MOD_NOREPEAT, 0x42)) {
System.out.println("Error");
return;
}

Pointer<MSG> msgPointer = Pointer.allocate(MSG.class);

try {
while (GetMessage(msgPointer, null, 0, 0) != 0) {
MSG msg = msgPointer.get();
if (msg.message() == WM_HOTKEY && msg.wParam() == id) {
System.out.println("YEAH");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
UnregisterHotKey(null, id);
}

Listening to key presses in Java without a UI component

As far as I know, there's no way to do this in straight Java. Since keyboard commands are handled by the OS, the only way to get Java to do this is to write some low level JNI. I've done something like this by writing an X event handler in C++ (for *nix based OS). Since key events in Java are per GUI component, there's no way to do this on a global scale. When I wrote the X event handle, I had the challenge of dealing with the limitation that only a single application at a time can grab a key. (XGrabKey).



Related Topics



Leave a reply



Submit