1
+ using System ;
2
+ using System . Diagnostics ;
3
+ using System . Runtime . InteropServices ;
4
+
5
+ namespace ComputerLock . Hooks ;
6
+ internal class SystemKeyHook : IDisposable
7
+ {
8
+ // ReSharper disable InconsistentNaming
9
+ private const int WH_KEYBOARD_LL = 13 ;
10
+ private const int WM_KEYDOWN = 0x0100 ;
11
+
12
+ private const int VK_LWIN = 0x5B ;
13
+ private const int VK_RWIN = 0x5C ;
14
+ private const int VK_LCONTROL = 0xA2 ;
15
+ private const int VK_RCONTROL = 0xA3 ;
16
+ // ReSharper restore InconsistentNaming
17
+
18
+ private int _hookId ;
19
+ private readonly HookDelegate _hookCallback ;
20
+
21
+ public delegate int HookDelegate ( int nCode , int wParam , IntPtr lParam ) ;
22
+
23
+ [ DllImport ( "user32.dll" ) ]
24
+ public static extern int SetWindowsHookEx ( int idHook , HookDelegate callback , IntPtr hInstance , uint threadId ) ;
25
+
26
+ [ DllImport ( "user32.dll" ) ]
27
+ public static extern int UnhookWindowsHookEx ( int idHook ) ;
28
+
29
+ [ DllImport ( "user32.dll" ) ]
30
+ public static extern int CallNextHookEx ( int idHook , int nCode , int wParam , IntPtr lParam ) ;
31
+
32
+ [ DllImport ( "kernel32.dll" ) ]
33
+ public static extern IntPtr GetModuleHandle ( string lpModuleName ) ;
34
+
35
+
36
+ public SystemKeyHook ( )
37
+ {
38
+ _hookCallback = KeyboardHookCallback ;
39
+ }
40
+
41
+ public void DisableSystemKey ( )
42
+ {
43
+ using Process curProcess = Process . GetCurrentProcess ( ) ;
44
+ string ? moduleName = curProcess . MainModule ? . ModuleName ;
45
+ if ( moduleName == null )
46
+ {
47
+ return ;
48
+ }
49
+ _hookId = SetWindowsHookEx ( WH_KEYBOARD_LL , _hookCallback , GetModuleHandle ( moduleName ) , 0 ) ;
50
+ }
51
+
52
+ private int KeyboardHookCallback ( int nCode , int wParam , IntPtr lParam )
53
+ {
54
+ if ( nCode >= 0 && wParam == WM_KEYDOWN )
55
+ {
56
+ int vkCode = Marshal . ReadInt32 ( lParam ) ;
57
+ if ( vkCode == VK_LWIN || vkCode == VK_RWIN || vkCode == VK_LCONTROL || vkCode == VK_RCONTROL )
58
+ {
59
+ return 1 ; // 阻止事件传递
60
+ }
61
+ }
62
+ return CallNextHookEx ( _hookId , nCode , wParam , lParam ) ;
63
+ }
64
+ public void Dispose ( )
65
+ {
66
+ UnhookWindowsHookEx ( _hookId ) ;
67
+ }
68
+ }
0 commit comments