0xXXXXXXXX上的指令引用0xXXXXXXXX处的内存,无法写入内存

时间:2013-07-18 14:56:32

标签: c# .net hook

尝试使用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();
    }

1 个答案:

答案 0 :(得分:3)

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