[ 来源:http://www.it55.com | 作者: | 时间:2008-01-11 | 收藏 | 推荐 ] 【大 中 小】
71 }
72 #endregion
73
74 钩子类型的枚举#region 钩子类型的枚举
75 public enum HookType : int
76 {
77 WH_JOURNALRECORD = 0,
78 WH_JOURNALPLAYBACK = 1,
79 WH_KEYBOARD = 2,
80 WH_GETMESSAGE = 3,
81 WH_CALLWNDPROC = 4,
82 WH_CBT = 5,
83 WH_SYSMSGFILTER = 6,
84 WH_MOUSE = 7,
85 WH_HARDWARE = 8,
86 WH_DEBUG = 9,
87 WH_SHELL = 10,
88 WH_FOREGROUNDIDLE = 11,
89 WH_CALLWNDPROCRET = 12,
90 WH_KEYBOARD_LL = 13,
91 WH_MOUSE_LL = 14
92 }
93 #endregion
94
95 虚键值的定义(参照WinUser.h中定义)#region 虚键值的定义(参照WinUser.h中定义)
96 public enum VirtualKeys
97 {
98 VK_SHIFT = 0x10,
99 VK_CONTROL = 0x11,
100 VK_MENU = 0x12, //ALT
101 VK_PAUSE = 0x13,
102 VK_CAPITAL = 0x14
103 }
104 #endregion
105
106 钩子委托#region 钩子委托
107 public delegate int HookProc(int code, IntPtr wParam, IntPtr lParam);
108 public delegate void HookEventHandler(object sender, HookEventArgs e);
109 #endregion
110
111 钩子事件参数#region 钩子事件参数
112 public class HookEventArgs : EventArgs
113 {
114 public int HookCode;
115 public IntPtr wParam;
116 public IntPtr lParam;
117 public Keys key;
118 public bool bAltKey;
119 public bool bCtrlKey;
120 }
121 #endregion
122
123 钩子类#region 钩子类
124 public class MyHook
125 {
126 调用Windows API#region 调用Windows API
127 [DllImport("user32.dll")]
128 static extern IntPtr SetWindowsHookEx(HookType hook, HookProc callback, IntPtr hMod, uint dwThreadId);
129
130 [DllImport("user32.dll")]
131 static extern bool UnhookWindowsHookEx(IntPtr hhk);
132
133 [DllImport("user32.dll")]
134 static extern int CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
135
136 [DllImport("user32.dll")]
137 static extern short GetKeyState(VirtualKeys nVirtKey);
138 #endregion
139
140 局部变量#region 局部变量
141 private IntPtr m_hook;
142 private HookType m_hooktype;
143 private HookProc m_hookproc;
144
145 private bool _bCallNext;
146
147 public bool CallNextProc
148 {
149 get { return _bCallNext; }
150 set { _bCallNext = value; }
151 }
152
153 #endregion
154
155 public event HookEventHandler HookInvoked;
156
157 public void Install()
158 {
159 m_hook = SetWindowsHookEx(m_hooktype, m_hookproc, IntPtr.Zero, (uint)AppDomain.GetCurrentThreadId());
160 }
161
162 public void Uninstall()
163 {
164 if (m_hook != IntPtr.Zero)
165 {
166 UnhookWindowsHookEx(m_hook);
167 }
168 }
169
170 public MyHook(HookType HookType)
171 {
172 m_hooktype = HookType;
173 if (m_hooktype == HookType.WH_KEYBOARD)
174 {
175 m_hookproc = new HookProc(KeyHookProcedure);
176 }
177 else if (m_hooktype == HookType.WH_CALLWNDPROC)
178 {
179 m_hookproc = new HookProc(CallProcHookProcedure);
180 }
181 }
182
183 protected int KeyHookProcedure(int code, IntPtr wParam, IntPtr lParam)
184 {
185 if (code != 0)
186 {
187 return CallNextHookEx(m_hook, code, wParam, lParam);
188 }
189
190 if (HookInvoked != null)
191 {
192 Keys key = (Keys)wParam.ToInt32();
(编辑:IT资讯之家 www.it55.com)