我试图用JNA捕捉窗口打开和关闭事件。我的目标是获得窗口标题。应该可以通过从User32 lib调用SetWindowsHookEx来安装WH_CBT钩子。此挂钩的回调函数是CBTProc。
默认情况下,JNA库不支持WH_CBT挂钩,我编写了自己的实现,但它不起作用。我仔细检查了CBTProc程序的签名,看起来没错,但是没有调用。
我想念一下吗?
这是代码。
public class CbtProcHook {
private static volatile boolean quit;
private static HHOOK hhk;
private static WinUser.HOOKPROC sysCmdHook;
interface CbtProc extends WinUser.HOOKPROC {
WinDef.LRESULT callback(int nCode, WinDef.WPARAM wParam, WinDef.LPARAM lParam);
}
public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
sysCmdHook = (CbtProc) (nCode, wParam, lParam) -> {
System.out.println("in callback. nCode=" + nCode + " wParam.intValue=" + wParam.intValue());
quit = true;
return lib.CallNextHookEx(hhk, 1, wParam, null);
};
// 5 = WH_CBT
hhk = lib.SetWindowsHookEx(5, sysCmdHook, hMod, 0);
System.out.println("hook installed");
new Thread() {
public void run() {
while (!quit) {
try {
Thread.sleep(500);
int error = Kernel32.INSTANCE.GetLastError();
if (error < 0) {
System.out.println("error=" + error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();
}
答案 0 :(得分:0)
为什么您将nCode
替换为1
而将lParam
替换为NULL
?
如果nCode
小于零,则必须在不进一步处理的情况下返回CallNextHookEx的结果
sysCmdHook = (CbtProc) (nCode, wParam, lParam) -> {
if(nCode<0)
return lib.CallNextHookEx(hhk, nCode, wParam, lParam);
System.out.println("in callback. nCode=" + nCode + " wParam.intValue=" + wParam.intValue());
quit = true;
return 0;
};
https://msdn.microsoft.com/en-us/library/windows/desktop/ms644977%28v=vs.85%29.aspx