0

尝试使用 SetWindowsHookEx 和 CallWndProc 实现 Windows 挂钩时出现此错误。我想知道我是否正确实施了钩子。这是代码:如果将其替换为 LowLevelKeyboardProc,此代码将用作键盘挂钩


    [DllImport("user32.dll")]
    static extern IntPtr SetWindowsHookEx(int idHook, CallWndProc callback, IntPtr hInstance, uint threadId);

    [DllImport("user32.dll")]
    static extern bool UnhookWindowsHookEx(IntPtr hInstance);

    [DllImport("user32.dll")]
    static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, int wParam, IntPtr lParam);

    [DllImport("kernel32.dll")]
    static extern IntPtr LoadLibrary(string lpFileName);

    private delegate IntPtr CallWndProc(int nCode, IntPtr wParam, IntPtr lParam);

    const int WH_CALLWNDPROC = 4;
    const int WM_PASTE = 0x302;
    private CallWndProc _proc = hookProc;

    private static IntPtr hhook = IntPtr.Zero;

    public void SetHook()
    {
        IntPtr hInstance = LoadLibrary("User32");
        hhook = SetWindowsHookEx(WH_CALLWNDPROC, _proc, hInstance, 0);
    }

    public static void UnHook()
    {
        UnhookWindowsHookEx(hhook);
    }

    public static IntPtr hookProc(int code, IntPtr wParam, IntPtr lParam)
    {
        if (code >= 0 && wParam == (IntPtr)WM_PASTE)
        {
            MessageBox.Show("Paste");
            return (IntPtr)1;
        }
        else
            return CallNextHookEx(hhook, code, (int)wParam, lParam);
    }

    private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        UnHook();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        SetHook();
    }
4

1 回答 1

3

传递给 SetWindowsHookEx 的模块句柄应该是您的 dll 的句柄,而不是“user32”。

于 2013-07-18T15:03:26.533 回答