//Dipose our Keyhook as it is not automatically handled by the GC public void DisposeKeyHook() { if (_keyHookWindowsHandle != IntPtr.Zero) { if (!DLLImports.UnhookWindowsHookEx(_keyHookWindowsHandle)) { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}."); } _keyHookWindowsHandle = IntPtr.Zero; _keyHookProc = null; } }
//An overload of the DisposeKeyHook function. After disposing the hook, we unsubscribe hookProc event from the _keyHookProc instead of setting the _KeyHookProc to null. public void DisposeKeyHook(HookProc hookProc) { if (_keyHookWindowsHandle != IntPtr.Zero) { if (!DLLImports.UnhookWindowsHookEx(_keyHookWindowsHandle)) { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}."); } _keyHookWindowsHandle = IntPtr.Zero; // ReSharper disable once DelegateSubtraction _keyHookProc -= hookProc; } }