如何使用JNA创建全局WH_GETMESSAGE钩子?

时间:2011-12-21 11:40:51

标签: hook jna

这是我测试钩子的代码,但是从不调用回调方法。我试图创建一个名为MSGSTRUCT扩展结构的类(仍然,不起作用),但我发现jna已经有类MSG,所以我用它代替。

谁能告诉我正确的方法呢?

import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HMODULE;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinUser.HHOOK;
import com.sun.jna.platform.win32.WinUser.HOOKPROC;
import com.sun.jna.platform.win32.WinUser.MSG;

public class GetMsgHookTest {

    public static final int WH_GETMESSAGE = 3;
    static HHOOK msgHook;   
    static HOOKPROC msgProc;

    public static void main(String[] args) {

        msgProc = new GetMsgProc() {

            @Override
            public LRESULT callback(int nCode, WPARAM wParam, MSG lParam) {
                System.out.println("get msg");
                return User32.INSTANCE.CallNextHookEx(msgHook, nCode, wParam, lParam.getPointer());
            }
        };

        HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
        msgHook = User32.INSTANCE.SetWindowsHookEx(WH_GETMESSAGE, msgProc, hMod, 0);

        MSG msg = new MSG();
        while (User32.INSTANCE.GetMessage(msg, null, 0, 0) != 0) {
            User32.INSTANCE.TranslateMessage(msg);
            User32.INSTANCE.DispatchMessage(msg);       
        }

        User32.INSTANCE.UnhookWindowsHookEx(msgHook);
    }

    public static interface GetMsgProc extends HOOKPROC {
        LRESULT callback(int nCode, WPARAM wParam, MSG lParam);
    }

}

0 个答案:

没有答案