JNA Keyboard Hook in Windows
It appears you need to call GetMessage
or PeekMessage
, which is odd - it is not mentioned in the documentation for Hooks or LowLevelKeyboardProc. I don't know enough about this part of the API to guess at the reason.
I just used the example classes:
import com.sun.jna.examples.win32.*;
public class Callback {
public static User32.HHOOK hHook;
public static User32.LowLevelKeyboardProc lpfn;
public static volatile boolean quit = false;
public static void main(String[] args) throws Exception {
W32API.HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
lpfn = new User32.LowLevelKeyboardProc() {
public W32API.LRESULT callback(int nCode, W32API.WPARAM wParam,
User32.KBDLLHOOKSTRUCT lParam) {
System.out.println("here");
quit = true;
return User32.INSTANCE.CallNextHookEx(hHook, nCode, wParam, lParam
.getPointer());
}
};
hHook = User32.INSTANCE.SetWindowsHookEx(User32.WH_KEYBOARD_LL, lpfn, hMod,
0);
if (hHook == null)
return;
User32.MSG msg = new User32.MSG();
while (!quit) {
User32.INSTANCE.PeekMessage(msg, null, 0, 0, 0);
Thread.sleep(100);
}
if (User32.INSTANCE.UnhookWindowsHookEx(hHook))
System.out.println("Unhooked");
}
}
A minimalist example:
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HINSTANCE;
import com.sun.jna.platform.win32.WinDef.LPARAM;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinUser.HOOKPROC;
public class MainTestKeyHook {
public static void main(String[] args) throws Exception {
HOOKPROC hookProc = new HOOKPROC_bg();
HINSTANCE hInst = Kernel32.INSTANCE.GetModuleHandle(null);
User32.HHOOK hHook = User32.INSTANCE.SetWindowsHookEx(User32.WH_KEYBOARD_LL, hookProc, hInst, 0);
if (hHook == null)
return;
User32.MSG msg = new User32.MSG();
System.err.println("Please press any key ....");
while (true) {
User32.INSTANCE.GetMessage(msg, null, 0, 0);
}
}
}
class HOOKPROC_bg implements HOOKPROC {
public HOOKPROC_bg() {
}
public LRESULT callback(int nCode, WPARAM wParam, LPARAM lParam) {
System.err.println("callback bbbnhkilhjkibh nCode: " + nCode);
return new LRESULT(0);
}
}