コード例 #1
0
        public override void InstallHook()
        {
            lock (_syncObject) {
                if (Status != DeviceHookStatus.Uninstalled && !Disposing)
                {
                    throw new SoftwareException("Keyboard hook has already been installed. Current Status is '{0}'", Status);
                }
                if (_hKeyboardHook == IntPtr.Zero)
                {
                    using (var process = Process.GetCurrentProcess()) {
                        //// Keep the delegate as a field to prevent garbage collection
                        _keyboardHookProcedure = KeyboardHookProc;
                        _hKeyboardHook         = WinAPI.USER32.SetWindowsHookEx(
                            WinAPI.USER32.HookType.WH_KEYBOARD_LL,
                            _keyboardHookProcedure,
                            //Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0])   // NOTE: 2021-08-03 removed since .NET 4+ and Core 3+ use new approach https://www.programmersought.com/article/51595908521/
                            WinAPI.KERNEL32.GetModuleHandle(null),
                            0
                            );

                        // If SetWindowsHookEx fails.
                        if (_hKeyboardHook == IntPtr.Zero && !Disposing)
                        {
                            throw new WindowsException(WinAPI.KERNEL32.GetLastError(),
                                                       "Windows did not allow the application to install a keyboard hook.");
                        }
                    }
                }
                Status = DeviceHookStatus.Disabled;
            }
        }
コード例 #2
0
 public override void UninstallHook()
 {
     if (Status == DeviceHookStatus.Uninstalled && !Disposing)
     {
         throw new SoftwareException("Mouse hook has not installed. Current Status is '{0}'", Status);
     }
     if (_hMouseHook != IntPtr.Zero)
     {
         if (!WinAPI.USER32.UnhookWindowsHookEx(_hMouseHook) && !Disposing)
         {
             throw new WindowsException(WinAPI.KERNEL32.GetLastError(), "Windows did not allow the application to uninstall mouse hook.");
         }
     }
     _hMouseHook         = IntPtr.Zero;
     _mouseHookProcedure = null;
     Status = DeviceHookStatus.Uninstalled;
 }