使用完鉤子後,要進行卸載,這個可以寫在析構函數中。
1
2 public void Stop() {
3 this.Stop (true, true, true);
4 }
5
6 public void Stop (bool uninstallMouseHook, bool uninstallKeyboardHook,
7 bool throwExceptions) {
8 // if mouse hook set and must be uninstalled
9 if (hMouseHook != IntPtr.Zero && uninstallMouseHook) {
10 // uninstall hook
11 bool retMouse = UnhookWindowsHookEx(hMouseHook);
12 // reset invalid handle
13 hMouseHook = IntPtr.Zero;
14 // if failed and exception must be thrown
15 if (retMouse == false && throwExceptions) {
16 // Returns the error code returned by the last unmanaged function
17 // called using platform invoke that has the DllImportAttribute.
18 // SetLastError flag set.
19 int errorCode = Marshal.GetLastWin32Error();
20 // Initializes and throws a new instance of the Win32Exception class
21 // with the specifIEd error.
22 throw new Win32Exception(errorCode);
23 }
24 }
25
26 // if keyboard hook set and must be uninstalled
27 if (hKeyboardHook != IntPtr.Zero && uninstallKeyboardHook) {
28 // uninstall hook
29 bool retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
30 // reset invalid handle
31 hKeyboardHook = IntPtr.Zero;
32 // if failed and exception must be thrown
33 if (retKeyboard == false && throwExceptions) {
34 // Returns the error code returned by the last unmanaged function
35 // called using platform invoke that has the DllImportAttribute.
36 // SetLastError flag set.
37 int errorCode = Marshal.GetLastWin32Error();
38 // Initializes and throws a new instance of the Win32Exception class
39 // with the specifIEd error.
40 throw new Win32Exception(errorCode);
41 }
42 }
43 }
44