private void InstallHook() { // Error check if (_handle != IntPtr.Zero) { throw new Exception("Hook is already installed"); } #region htype int htype = 0; switch (_hookType) { case HookTypes.Mouse: htype = WinApi.WH_MOUSE_LL; break; case HookTypes.Keyboard: htype = WinApi.WH_KEYBOARD_LL; break; default: throw new Exception("HookType is not supported"); } #endregion // Delegate to recieve message _HookProc = HookProc; // Hook // Ed Obeda suggestion for .net 4.0 //_hHook = WinApi.SetWindowsHookEx(htype, _HookProc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0); _handle = WinApi.SetWindowsHookEx(htype, _HookProc, Process.GetCurrentProcess().MainModule.BaseAddress, 0); int lastWin32Error = Marshal.GetLastWin32Error(); // Error check if (_handle == IntPtr.Zero) { throw new Win32Exception(lastWin32Error); } }
/// <summary> /// Installs the actual unsafe hook /// </summary> private void InstallHook() { /// Error check if (Handle != 0) { throw new Exception("Hook is already installed"); } #region htype int htype = 0; switch (HookType) { case HookTypes.Mouse: htype = WinApi.WH_MOUSE_LL; break; case HookTypes.Keyboard: htype = WinApi.WH_KEYBOARD_LL; break; default: throw new Exception("HookType is not supported"); } #endregion /// Delegate to recieve message _HookProc = new HookProcCallBack(HookProc); /// Hook //_hHook = WinApi.SetWindowsHookEx(htype, _HookProc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0); _hHook = WinApi.SetWindowsHookEx(htype, _HookProc, System.Diagnostics.Process.GetCurrentProcess().MainModule.BaseAddress, 0); /// Error check if (Handle == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } }