internal static extern IntPtr SetWinEventHook( uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventProcDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags );
private static extern IntPtr SetWinEventHook(int minEvent, int maxEvent, IntPtr hModule, WinEventProcDelegate proc, int procId, int threadId, int flags);
protected void InstallHook(HookType hookType, bool global) { lock (HookLock) { // If hook is installed already then return. _hookType = hookType; if (hook1handleRef.Handle != IntPtr.Zero) { return; } string lpModuleName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName; var hMod = NativeMethods.GetModuleHandle(lpModuleName); // Assign Virtual function. _Hook1Procedure = new HookProcDelegate(Hook1Procedure); IntPtr hook1Handle; if (hookType == HookType.WH_MOUSE) { uint threadId = NativeMethods.GetCurrentThreadId(); // Listen for events. hook1Handle = NativeMethods.SetWindowsHookEx( (uint)hookType, _Hook1Procedure, hMod, // Associate hook procedure with current application/thread only. threadId ); if (hook1Handle == IntPtr.Zero) { var ex = new Win32Exception(); throw new Exception(ex.Message); } _Hook2Procedure = new WinEventProcDelegate(Hook2Procedure); // Listen for name change changes across all processes/threads on current desktop... var hook2Handle = NativeMethods.SetWinEventHook( EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, IntPtr.Zero, _Hook2Procedure, 0, // Associate hook procedure with current application/thread only. global ? 0 : threadId, WINEVENT_OUTOFCONTEXT ); if (hook2Handle == IntPtr.Zero) { var ex = new Win32Exception(); throw new Exception(ex.Message); } hook2handleRef = new HandleRef(null, hook2Handle); // Listen for name change changes across all processes/threads on current desktop... var hook3Handle = NativeMethods.SetWinEventHook( EVENT_OBJECT_SHOW, EVENT_OBJECT_SHOW, IntPtr.Zero, _Hook2Procedure, 0, // Associate hook procedure with current application/thread only. global ? 0 : threadId, WINEVENT_OUTOFCONTEXT ); if (hook3Handle == IntPtr.Zero) { var ex = new Win32Exception(); throw new Exception(ex.Message); } hook3handleRef = new HandleRef(null, hook3Handle); } else { // Listen for events. hook1Handle = NativeMethods.SetWindowsHookEx((uint)hookType, _Hook1Procedure, hMod, 0); if (hook1Handle == IntPtr.Zero) { var ex = new Win32Exception(); throw new Exception(ex.Message); } } hook1handleRef = new HandleRef(null, hook1Handle); } }