WH_MOUSE_LL没有响应注入的事件

时间:2013-11-15 18:02:12

标签: c# .net winapi mouseevent hook

this unanswered question类似,我们使用SendInput / mouse_event / SetCursorPos以编程方式移动鼠标并发送鼠标点击。我们还希望使用WH_MOUSE_LL窗口挂钩捕获计算机上的所有鼠标事件。我们使用包含flags属性的MSLLHOOKSTRUCT,该属性专门用于识别注入的鼠标事件。但是,我们的回调永远不会被注入事件调用。

var threadId = 0U;
var moduleHandle = GetModuleHandle("user32");

IntPtr hookId = SetWindowsHookEx(WH_MOUSE_LL, ourCallback, moduleHandle, threadId);

if (hookId == IntPtr.Zero)
{
    log.Error("Could not start getting global mouse messages.");

    throw new System.ComponentModel.Win32Exception();
}

我们的hookId永远不会IntPtr.Zero,并且UnhookWindowsHookEx将其删除会成功,这意味着确实存在错误。

为什么我们没有收到SendInput / mouse_event / SetCursorPos生成的事件?

1 个答案:

答案 0 :(得分:0)

你应该像这样使用SetWindowsHookEx

private delegate IntPtr WindowHookHandler(int nCode, IntPtr wParam, IntPtr lParam);
private static WindowHookHandler MouseHookHandler = myCallbackFunction;

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, WindowHookHandler lpfn, IntPtr hMod, uint dwThreadId);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);

private static IntPtr MouseHook = IntPtr.Zero;

private static IntPtr SetHook(int hookId, WindowHookHandler callbackFunc)
{
    using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())
    {
        using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(hookId, callbackFunc, GetModuleHandle(curModule.ModuleName), 0);
        }
    }
}

private static void SomeFunction()
{
    MouseHook = SetHook(WH_MOUSE_LL, MouseHookHandler);

    // message loop here
    // waiting for events

    UnhookWindowsHookEx(MouseHook);
}

private static IntPtr myCallbackFunction(int nCode, IntPtr wParam, IntPtr lParam)
{
    // do something here

    // ALWAYS return like this!
    return CallNextHookEx(MouseHook, nCode, wParam, lParam);
}

我曾尝试测试LLMHF_INJECTED的标志,但它从未奏效。 我改用了dwExtraInfo字段。如果要创建事件,请在其中放置一些唯一数据,并在事件监听器中监视这些数据。