There is a console application with this code

static void Main(string[] args) { var hproc = new Hooks.HookProc(Hooks.MouseHookProc); var hHook = Hooks.SetWindowsHookEx(Hooks.WH_MOUSE, hproc, (IntPtr)0, AppDomain.GetCurrentThreadId()); Console.WriteLine(hHook); Console.ReadKey(); Hooks.UnhookWindowsHookEx(hHook); } 

and here's a hooks class and a couple of structures

 public class Hooks { public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam); static int hHook = 0; public const int WH_MOUSE = 7; // Повесить хук [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); // Убрать хук [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern bool UnhookWindowsHookEx(int idHook); // Послать то что выловили дальше [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int CallNextHookEx(int idHook, int nCode,IntPtr wParam, IntPtr lParam); public static int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) { var MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct)); if (nCode < 0) { return CallNextHookEx(hHook, nCode, wParam, lParam); } else { var strCaption = "x = " + MyMouseHookStruct.pt.x.ToString("d") + " y = " + MyMouseHookStruct.pt.y.ToString("d"); Console.WriteLine(strCaption); return CallNextHookEx(hHook, nCode, wParam, lParam); } } } [StructLayout(LayoutKind.Sequential)] public class MouseHookStruct { public POINT pt; public int hwnd; public int wHitTestCode; public int dwExtraInfo; } [StructLayout(LayoutKind.Sequential)] public class POINT { public int x; public int y; } 

As I understand it, the MouseHookProc procedure should be invoked with mouse actions. But nothing happens. What am I doing wrong?

  • Do you have confidence that the hook is established? SetWindowsHookEx () returned non 0? - nzeemin
  • @nzeemin,, not 0 - iRumba
  • Try to comment out in MouseHookProc everything except calls to CallNextHookEx () and add Console.WriteLine () at the very beginning of the method. If nothing is written, then it is necessary to dig in the direction of correctly specifying types for marshalling. - nzeemin
  • @nzeemin, this is not necessary. I put a breakpoint at the beginning of this function. To no avail. No call in there - iRumba
  • may need in the class: public int hHook = 0; and then after receiving it, assign it to the class: Hooks.hHook = Hooks.SetWindowsHookEx (Hooks.WH_MOUSE, hproc, (IntPtr) 0, AppDomain.GetCurrentThreadId ()); - Konst

1 answer 1

WH_MOUSE = 7; replace with WH_MOUSE_LL = 14

  • Try to write more detailed answers. Explain what is the basis of your statement? - Nicolas Chabanovsky