gpt4 book ai didi

Java JNA 使用 Keyhook 回调

转载 作者:太空宇宙 更新时间:2023-11-04 13:30:07 27 4
gpt4 key购买 nike

我正在寻找使用 JNA 的 keyhook 库,并在他们的 github 上找到了一个演示

public final class Test {

private static volatile boolean quit;
private static WinUser.HHOOK hhk;
private static WinUser.LowLevelKeyboardProc keyboardHook;

public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
WinDef.HMODULE hMod = Kernel32Direct.GetModuleHandle(null);
keyboardHook = new WinUser.LowLevelKeyboardProc() {
@Override
public WinDef.LRESULT callback(int nCode, WinDef.WPARAM wParam, WinUser.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;
}
break;
}
}

Pointer ptr = info.getPointer();
long peer = Pointer.nativeValue(ptr);
return lib.CallNextHookEx(hhk, nCode, wParam, new WinDef.LPARAM(peer));
}
};
hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
System.out.println("Keyboard hook installed, type anywhere, 'q' to quit");
new Thread() {
@Override
public void run() {
while (!quit) {
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();

// This bit never returns from GetMessage
int result;
WinUser.MSG msg = new WinUser.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);
}

}

我想知道如何像使用 Swing/AWT 事件一样使用按键?

例如:如果用户键入字母 h,我该如何处理才能使按键不会比我的键盘 Hook 进一步处理并消耗它?

谢谢!

最佳答案

为了使用 key ,您必须返回新的 WinDef.LRESULT(1)。

示例:

               keyboardHook = (nCode, wParam, info) -> {
if (nCode >= 0) {
NativeKeyEvent event = new NativeKeyEvent(info.vkCode, info.time);
switch (wParam.intValue()) {
case WinUser.WM_KEYDOWN:
case WinUser.WM_SYSKEYDOWN:
dispatch(EventType.KEY_DOWN, event);
break;
case WinUser.WM_KEYUP:
case WinUser.WM_SYSKEYUP:
dispatch(EventType.KEY_UP, event);
break;
}
if (event.consumed()) {
return new WinDef.LRESULT(1);
}
}
return new WinDef.LRESULT(0);
};

关于Java JNA 使用 Keyhook 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32282954/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com