1 //键盘钩子锁定不需要的键
2 public const uint SND_SYNC = 0x0;
3 public const uint SND_ASYNC = 0x1;
4 public const uint SND_NODEFAULT = 0x2;
5 public const uint SND_MEMORY = 0x4;
6 public const uint SND_ALIAS = 0x10000;
7 public const uint SND_FILENAME = 0x20000;
8 public const uint SND_RESOURCE = 0x40004;
9 public const uint SND_ALIAS_ID = 0x110000;
10 public const uint SND_ALIAS_START = 0;
11 public const uint SND_LOOP = 0x8;
12 public const uint SND_NOSTOP = 0x10;
13 public const uint SND_VALID = 0x1F;
14 public const uint SND_NOWAIT = 0x2000;
15 public const uint SND_VALIDFLAGS = 0x17201F;
16 public const uint SND_RESERVED = 0xFF000000;
17 public const uint SND_TYPE_MASK = 0x170007;
18 internal enum HookType //枚举,钩子的类型
19 {
20 MsgFilter = -1,
21 JournalRecord = 0,
22 JournalPlayback = 1,
23 Keyboard = 2,
24 GetMessage = 3,
25 CallWndProc = 4,
26 CBT = 5,
27 SysMsgFilter = 6,
28 Mouse = 7,
29 Hardware = 8,
30 Debug = 9,
31 Shell = 10,
32 ForegroundIdle = 11,
33 CallWndProcRet = 12,
34 KeyboardLL = 13,
35 MouseLL = 14,
36 };
37 IntPtr _nextHookPtr; //记录Hook编号
38 internal delegate IntPtr HookProc(int code, IntPtr wparam, IntPtr lparam);
39
40 IntPtr MyHookProc(int code, IntPtr wparam, IntPtr lparam)
41 {
42 //测试将键盘上不需要的键给屏蔽掉,
85 }
86 //函数指针
87 HookProc myhookProc;
88 //只要知道keyCode即可屏蔽所有功能键
89 //挂上钩子
90 public void SetHook()
91 {
92 if (_nextHookPtr != IntPtr.Zero)
93 return;
94 myhookProc = new HookProc(MyHookProc);
95 _nextHookPtr = SetWindowsHookEx((int)HookType.Keyboard, myhookProc, IntPtr.Zero, GetCurrentThreadId()); //加到Hook链中
96
97 //将当前的非英文输入法立即转换为英文输入法
98 //问题是:不同的计算机获取的il.handle的数据是不一样的,因此这种方法也控制不了的。
99 //InputLanguageCollection ilc = InputLanguage.InstalledInputLanguages;
100 //foreach (InputLanguage il in ilc)
101 //{
102 // if (il.Handle == (IntPtr)0x04090804) //如果输入法指针为0x04090804,也就是英文输入法。
103 // InputLanguage.CurrentInputLanguage = il;
104
105 //}
106 //获取输入法全角的信息或者是半角的信息。
107 }
108 //解除钩子
109 public void UnHook()
110 {
111 if (_nextHookPtr != IntPtr.Zero)
112 {
113 UnhookWindowsHookEx(_nextHookPtr);
114 _nextHookPtr = IntPtr.Zero;
115 }
116 }
117
118 [DllImport("kernel32.dll")]
119 static extern int GetCurrentThreadId(); //取得当前线程编号的API
120 [DllImport("User32.dll")]
121 internal extern static void UnhookWindowsHookEx(IntPtr handle); //取消Hook的API
122 [DllImport("User32.dll")]
123 internal extern static IntPtr SetWindowsHookEx(int idHook, [MarshalAs(UnmanagedType.FunctionPtr)] HookProc lpfn, IntPtr hinstance, int threadID); //设置Hook的API
124 [DllImport("User32.dll")]
125 internal extern static IntPtr CallNextHookEx(IntPtr handle, int code, IntPtr wparam, IntPtr lparam);
126
127
当要用的时候,在所需添加的界面中加入钩子代码:SetHook();
当用完了或跳转窗体时需加入释放钩子代码: UnHook();
你会了吗?