Question

I am trying to hook mouse click event to a windows application which is made of C# as well.

This is my code;

private const int WH_MOUSE = 7;

[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

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

private static IntPtr SetHook(LowLevelMouseProc proc)
{
    IntPtr hWnd = IntPtr.Zero;
    uint processId = 0;
    uint threadID = 0;
    string moduleName   = string.Empty;
    Process[] localAll = Process.GetProcesses();
    string toFindModule  ="windowsformsapplication1.exe";
    foreach (Process p in localAll)
    {
        if (p.MainWindowHandle != IntPtr.Zero)
        {
            ProcessModule pm = GetModule(p);
            if (pm != null && p.MainModule.FileName.ToLower().IndexOf(toFindModule) > -1)
            {
                hWnd = p.MainWindowHandle;
                threadID = GetWindowThreadProcessId(hWnd, out processId);
                break;
            }
        }
    }

    IntPtr ret = SetWindowsHookEx(WH_MOUSE, proc, IntPtr.Zero, threadID);

    return ret;
}

I have assured the thread ID of WindowsFormsApplication1.exe.

But, IntPtr ret = SetWindowsHookEx(WH_MOUSE, proc, IntPtr.Zero, threadID); always returns 0;

So, I am enable hook the mouse click event.

Is there something wrong with my code?

I even tried calc.exe, but no luck either.

EDIT

And I am pretty sure that I captured correct thread id of my target winform.

enter image description here

Was it helpful?

Solution

You cannot use a global WH_MOUSE hook from C#, or indeed a thread specific WH_MOUSE hook for a thread in a different process. That requires an unmanaged DLL.

From managed code you need to use WH_MOUSE_LL, the low-level mouse hook. If you really need WH_MOUSE then you will need to write the hook in native code so that the DLL can be injected into the target process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top