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.