I need global hotkey support for my Java application.
I came up with some code (mostly copied over), but it doesn't works.
HotkeyManager.java:
import java.awt.event.KeyEvent;
public class HotkeyManager extends Thread {
public static void register() {
User32.RegisterHotKey(null, 1, 0x000, KeyEvent.VK_F);
new HotkeyManager().start();
}
public HotkeyManager() {
}
@Override
public void run() {
MSG msg = new MSG();
while (true) {
while (User32.PeekMessage(msg, null, 0, 0, User32.PM_REMOVE)) {
if (msg.message == User32.WM_HOTKEY) {
System.out.println("Hotkey pressed with id: " + msg.wParam);
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
User32.java:
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import com.sun.jna.Pointer;
import com.sun.jna.win32.W32APIOptions;
public class User32 {
static {
Native.register(NativeLibrary.getInstance("user32", W32APIOptions.DEFAULT_OPTIONS));
}
public static final int MOD_ALT = 0x0001;
public static final int MOD_CONTROL = 0x0002;
public static final int MOD_SHIFT = 0x0004;
public static final int MOD_WIN = 0x0008;
public static final int WM_HOTKEY = 0x0312;
public static final int PM_REMOVE = 0x0001;
public static native boolean RegisterHotKey(Pointer hWnd, int id, int fsModifiers, int vk);
public static native boolean UnregisterHotKey(Pointer hWnd, int id);
public static native boolean PeekMessage(MSG lpMsg, Pointer hWnd, int wMsgFilterMin, int wMsgFilterMax, int wRemoveMsg);
}
MSG.java:
import java.util.Arrays;
import java.util.List;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
public class MSG extends Structure {
public Pointer hWnd;
public int lParam;
public int message;
public int time;
public int wParam;
public int x;
public int y;
@Override
protected List getFieldOrder() {
return Arrays.asList(new String[]{"hWnd", "lParam", "message", "time", "wParam", "x", "y"});
}
}
It does registers hotkey (pressing "F" in system results nothing while program is running), but I never get any output to the console. What's wrong? Also I'm aware of jintellitype and jnativehook. I can't use first, and as for second - it always listens to all the hardware events, including mouse movements and all key presses, I will only use it as last resort.
I figured it. I have to register hotkey in the same thread I'm listening for messages. User32.RegisterHotKey(null, 1, 0x000, KeyEvent.VK_F); goes into run() and everything works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With