/// <summary> /// Insert a low level hook to the current window, or hook to all windows in the system. /// </summary> /// <param name="Global">Specifies if HookDll is injected to all processes</param> public Hook(HookType hooktype, bool Global, IntPtr hWndTarget) { MessageHandler = new MessageLoop(WindowsMessages.WM_COPYDATA); MessageHandler.MessageCallback += MessageHandler_WndProc; this.Global = Global; HookType = hooktype; if (HookType == HookType.WH_SYSMSGFILTER) { Global = true; } //Set Hook uint HookEnabled = 0; if (Global) { HookEnabled = HookDll.SetHook((int)HookType, true, (uint)0, MessageHandler.Handle, hWndTarget); } else { HookEnabled = HookDll.SetHook((int)HookType, true, HookDll.GetCurrentThreadId(), MessageHandler.Handle, hWndTarget); } if (HookEnabled != 0) { throw new Win32Exception((int)HookEnabled); } }
/// <summary> /// Unhooks the hook and disposes the messageloop /// </summary> public void Dispose() { HookDll.SetHook(0, false, 0, IntPtr.Zero, IntPtr.Zero); MessageHandler.MessageCallback -= MessageHandler_WndProc; MessageHandler.Close(); MessageHandler.Dispose(); }
/// <summary> /// Inserts a low level hook to the specified process /// </summary> /// <param name="ToWatch">Process to intercept messages</param> public Hook(HookType hooktype, Process ToWatch, IntPtr hWndTarget) { MessageHandler = new MessageLoop(WindowsMessages.WM_COPYDATA); MessageHandler.MessageCallback += MessageHandler_WndProc; HookType = hooktype; uint TID = (uint)ToWatch.Threads[0].Id; if (HookType == HookType.WH_SYSMSGFILTER) { TID = 0; } uint HookEnabled = HookDll.SetHook((int)HookType, true, TID, MessageHandler.Handle, hWndTarget); if (HookEnabled != 0) { throw new Win32Exception((int)HookEnabled); } }