C# 实现WindowsHook 类

 

  1 None.gif using  System;
  2 None.gif using  System.Runtime.InteropServices;
  3 None.gif using  System.Reflection;
  4 None.gif using  System.Threading;
  5 None.gif
  6 None.gif using  System.Windows.Forms;
  7 None.gif
  8 None.gif
  9 ExpandedBlockStart.gifContractedBlock.gif namespace  GlobalHookDemo   dot.gif {
 10InBlock.gif    
 11ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
 12InBlock.gif    /// This class allows you to tap keyboard and mouse and / or to detect their activity even when an 
 13InBlock.gif    /// application runes in background or does not have any user interface at all. This class raises 
 14InBlock.gif    /// common .NET events with KeyEventArgs and MouseEventArgs so you can easily retrive any information you need.
 15InBlock.gif    /// </summary>
 16InBlock.gif    /// <remarks>
 17InBlock.gif    ///     created by - Georgi
 18InBlock.gif    ///     created on - 22.05.2004 13:08:01
 19ExpandedSubBlockEnd.gif    /// </remarks>

 20ExpandedSubBlockStart.gifContractedSubBlock.gif    public class UserActivityHook : object dot.gif{
 21InBlock.gif        
 22ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 23InBlock.gif        /// Default constructor - starts hooks automatically
 24ExpandedSubBlockEnd.gif        /// </summary>

 25ExpandedSubBlockStart.gifContractedSubBlock.gif        public UserActivityHook() dot.gif{
 26InBlock.gif            Start();
 27ExpandedSubBlockEnd.gif        }

 28InBlock.gif        
 29ExpandedSubBlockStart.gifContractedSubBlock.gif        ~UserActivityHook() dot.gif
 30InBlock.gif            Stop();
 31ExpandedSubBlockEnd.gif        }
 
 32InBlock.gif
 33InBlock.gif        public event MouseEventHandler OnMouseActivity;
 34InBlock.gif        public event KeyEventHandler KeyDown;
 35InBlock.gif        public event KeyPressEventHandler KeyPress;
 36InBlock.gif        public event KeyEventHandler KeyUp;
 37InBlock.gif
 38InBlock.gif        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
 39InBlock.gif
 40InBlock.gif        static int hMouseHook = 0//Declare mouse hook handle as int.
 41InBlock.gif        static int hKeyboardHook = 0//Declare keyboard hook handle as int.
 42InBlock.gif
 43InBlock.gif        //values from Winuser.h in Microsoft SDK.
 44InBlock.gif        public const int WH_MOUSE_LL     = 14;    //mouse hook constant
 45InBlock.gif        public const int WH_KEYBOARD_LL = 13;    //keyboard hook constant    
 46InBlock.gif
 47InBlock.gif        HookProc MouseHookProcedure; //Declare MouseHookProcedure as HookProc type.
 48InBlock.gif        HookProc KeyboardHookProcedure; //Declare KeyboardHookProcedure as HookProc type.
 49InBlock.gif            
 50InBlock.gif
 51InBlock.gif        //Declare wrapper managed POINT class.
 52InBlock.gif        [StructLayout(LayoutKind.Sequential)]
 53InBlock.gif        public class POINT 
 54ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 55InBlock.gif            public int x;
 56InBlock.gif            public int y;
 57ExpandedSubBlockEnd.gif        }

 58InBlock.gif
 59InBlock.gif        //Declare wrapper managed MouseHookStruct class.
 60InBlock.gif        [StructLayout(LayoutKind.Sequential)]
 61InBlock.gif        public class MouseHookStruct 
 62ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 63InBlock.gif            public POINT pt;
 64InBlock.gif            public int hwnd;
 65InBlock.gif            public int wHitTestCode;
 66InBlock.gif            public int dwExtraInfo;
 67ExpandedSubBlockEnd.gif        }

 68InBlock.gif
 69InBlock.gif        //Declare wrapper managed KeyboardHookStruct class.
 70InBlock.gif        [StructLayout(LayoutKind.Sequential)]
 71InBlock.gif        public class KeyboardHookStruct
 72ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 73InBlock.gif            public int vkCode;    //Specifies a virtual-key code. The code must be a value in the range 1 to 254. 
 74InBlock.gif            public int scanCode; // Specifies a hardware scan code for the key. 
 75InBlock.gif            public int flags;  // Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
 76InBlock.gif            public int time; // Specifies the time stamp for this message.
 77InBlock.gif            public int dwExtraInfo; // Specifies extra information associated with the message. 
 78ExpandedSubBlockEnd.gif        }

 79InBlock.gif
 80InBlock.gif
 81InBlock.gif        //Import for SetWindowsHookEx function.
 82InBlock.gif        //Use this function to install a hook.
 83InBlock.gif        [DllImport("user32.dll",CharSet=CharSet.Auto,
 84InBlock.gif            CallingConvention=CallingConvention.StdCall)]
 85InBlock.gif        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, 
 86InBlock.gif            IntPtr hInstance, int threadId);
 87InBlock.gif
 88InBlock.gif        //Import for UnhookWindowsHookEx.
 89InBlock.gif        //Call this function to uninstall the hook.
 90InBlock.gif        [DllImport("user32.dll",CharSet=CharSet.Auto,
 91InBlock.gif             CallingConvention=CallingConvention.StdCall)]
 92InBlock.gif        public static extern bool UnhookWindowsHookEx(int idHook);
 93InBlock.gif        
 94InBlock.gif        //Import for CallNextHookEx.
 95InBlock.gif        //Use this function to pass the hook information to next hook procedure in chain.
 96InBlock.gif        [DllImport("user32.dll",CharSet=CharSet.Auto,
 97InBlock.gif             CallingConvention=CallingConvention.StdCall)]
 98InBlock.gif        public static extern int CallNextHookEx(int idHook, int nCode, 
 99InBlock.gif            Int32 wParam, IntPtr lParam);  
100InBlock.gif
101InBlock.gif        public void Start()
102ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
103InBlock.gif            // install Mouse hook 
104InBlock.gif            if(hMouseHook == 0)
105ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
106InBlock.gif                // Create an instance of HookProc.
107InBlock.gif                MouseHookProcedure = new HookProc(MouseHookProc);
108InBlock.gif
109InBlock.gif                hMouseHook = SetWindowsHookEx( WH_MOUSE_LL,
110InBlock.gif                    MouseHookProcedure, 
111InBlock.gif                    Marshal.GetHINSTANCE(
112InBlock.gif                        Assembly.GetExecutingAssembly().GetModules()[0]),
113InBlock.gif                    0);
114InBlock.gif
115InBlock.gif                //If SetWindowsHookEx fails.
116ExpandedSubBlockStart.gifContractedSubBlock.gif                if(hMouseHook == 0 )    dot.gif{
117InBlock.gif                    Stop();
118InBlock.gif                    throw new Exception("SetWindowsHookEx failed.");
119ExpandedSubBlockEnd.gif                }

120ExpandedSubBlockEnd.gif            }

121InBlock.gif            
122InBlock.gif            // install Keyboard hook 
123InBlock.gif            if(hKeyboardHook == 0)
124ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
125InBlock.gif                KeyboardHookProcedure = new HookProc(KeyboardHookProc);
126InBlock.gif                hKeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL,
127InBlock.gif                    KeyboardHookProcedure, 
128InBlock.gif                    Marshal.GetHINSTANCE(
129InBlock.gif                    Assembly.GetExecutingAssembly().GetModules()[0]),
130InBlock.gif                    0);
131InBlock.gif
132InBlock.gif                //If SetWindowsHookEx fails.
133ExpandedSubBlockStart.gifContractedSubBlock.gif                if(hKeyboardHook == 0 )    dot.gif{
134InBlock.gif                    Stop();
135InBlock.gif                    throw new Exception("SetWindowsHookEx ist failed.");
136ExpandedSubBlockEnd.gif                }

137ExpandedSubBlockEnd.gif            }

138ExpandedSubBlockEnd.gif        }

139InBlock.gif
140InBlock.gif        public void Stop()
141ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
142InBlock.gif            bool retMouse =true;
143InBlock.gif            bool retKeyboard = true;
144InBlock.gif            if(hMouseHook != 0)
145ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
146InBlock.gif                retMouse = UnhookWindowsHookEx(hMouseHook);
147InBlock.gif                hMouseHook = 0;
148ExpandedSubBlockEnd.gif            }
 
149InBlock.gif            
150InBlock.gif            if(hKeyboardHook != 0)
151ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
152InBlock.gif                retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
153InBlock.gif                hKeyboardHook = 0;
154ExpandedSubBlockEnd.gif            }
 
155InBlock.gif            
156InBlock.gif            //If UnhookWindowsHookEx fails.
157InBlock.gif            if (!(retMouse && retKeyboard)) throw new Exception("UnhookWindowsHookEx failed.");
158ExpandedSubBlockEnd.gif        }

159InBlock.gif
160InBlock.gif
161InBlock.gif
162InBlock.gif          private const int WM_MOUSEMOVE = 0x200;
163InBlock.gif          private const int WM_LBUTTONDOWN = 0x201;
164InBlock.gif          private const int WM_RBUTTONDOWN = 0x204;
165InBlock.gif          private const int WM_MBUTTONDOWN = 0x207;
166InBlock.gif          private const int WM_LBUTTONUP = 0x202;
167InBlock.gif          private const int WM_RBUTTONUP = 0x205;
168InBlock.gif          private const int WM_MBUTTONUP = 0x208;
169InBlock.gif          private const int WM_LBUTTONDBLCLK = 0x203;
170InBlock.gif          private const int WM_RBUTTONDBLCLK = 0x206;
171InBlock.gif        private const int WM_MBUTTONDBLCLK = 0x209;
172InBlock.gif
173InBlock.gif        private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
174ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
175InBlock.gif            // if ok and someone listens to our events
176ExpandedSubBlockStart.gifContractedSubBlock.gif            if ((nCode >= 0&& (OnMouseActivity!=null)) dot.gif{
177InBlock.gif                
178InBlock.gif                MouseButtons button=MouseButtons.None;
179InBlock.gif                switch (wParam)
180ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
181InBlock.gif                    case WM_LBUTTONDOWN: 
182InBlock.gif                    //case WM_LBUTTONUP: 
183InBlock.gif                    //case WM_LBUTTONDBLCLK: 
184InBlock.gif                        button=MouseButtons.Left; 
185InBlock.gif                        break;
186InBlock.gif                    case WM_RBUTTONDOWN: 
187InBlock.gif                    //case WM_RBUTTONUP: 
188InBlock.gif                    //case WM_RBUTTONDBLCLK: 
189InBlock.gif                        button=MouseButtons.Right; 
190InBlock.gif                        break;
191InBlock.gif                    case WM_MBUTTONDOWN:
192InBlock.gif                        button=MouseButtons.Middle;
193InBlock.gif                        break;
194ExpandedSubBlockEnd.gif                }

195InBlock.gif                int clickCount=0;
196InBlock.gif                if (button!=MouseButtons.None)
197InBlock.gif                    if (wParam==WM_LBUTTONDBLCLK || wParam==WM_RBUTTONDBLCLK) clickCount=2;
198InBlock.gif                    else clickCount=1;
199InBlock.gif                
200InBlock.gif                //Marshall the data from callback.
201InBlock.gif                MouseHookStruct MyMouseHookStruct = (MouseHookStruct) Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
202InBlock.gif                MouseEventArgs e=new MouseEventArgs(
203InBlock.gif                                                    button, 
204InBlock.gif                                                    clickCount, 
205InBlock.gif                                                    MyMouseHookStruct.pt.x, 
206InBlock.gif                                                    MyMouseHookStruct.pt.y, 
207InBlock.gif                                                    0 );
208InBlock.gif                OnMouseActivity(this, e);
209ExpandedSubBlockEnd.gif            }

210InBlock.gif            return CallNextHookEx(hMouseHook, nCode, wParam, lParam); 
211ExpandedSubBlockEnd.gif        }

212InBlock.gif
213InBlock.gif
214InBlock.gif        //The ToAscii function translates the specified virtual-key code and keyboard state to the corresponding character or characters. The function translates the code using the input language and physical keyboard layout identified by the keyboard layout handle.
215InBlock.gif        [DllImport("user32")] 
216InBlock.gif        public static extern int ToAscii(int uVirtKey, //[in] Specifies the virtual-key code to be translated. 
217InBlock.gif                                         int uScanCode, // [in] Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up (not pressed). 
218InBlock.gif                                         byte[] lpbKeyState, // [in] Pointer to a 256-byte array that contains the current keyboard state. Each element (byte) in the array contains the state of one key. If the high-order bit of a byte is set, the key is down (pressed). The low bit, if set, indicates that the key is toggled on. In this function, only the toggle bit of the CAPS LOCK key is relevant. The toggle state of the NUM LOCK and SCROLL LOCK keys is ignored.
219InBlock.gif                                         byte[] lpwTransKey, // [out] Pointer to the buffer that receives the translated character or characters. 
220InBlock.gif                                         int fuState); // [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise. 
221InBlock.gif
222InBlock.gif        //The GetKeyboardState function copies the status of the 256 virtual keys to the specified buffer. 
223InBlock.gif        [DllImport("user32")] 
224InBlock.gif        public static extern int GetKeyboardState(byte[] pbKeyState);
225InBlock.gif
226InBlock.gif        private const int WM_KEYDOWN         = 0x100;
227InBlock.gif        private const int WM_KEYUP             = 0x101;
228InBlock.gif        private const int WM_SYSKEYDOWN     = 0x104;
229InBlock.gif        private const int WM_SYSKEYUP         = 0x105;
230InBlock.gif
231InBlock.gif        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
232ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
233InBlock.gif            // it was ok and someone listens to events
234InBlock.gif            if ((nCode >= 0&& (KeyDown!=null || KeyUp!=null || KeyPress!=null))
235ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
236InBlock.gif                KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct) Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
237InBlock.gif                // raise KeyDown
238InBlock.gif                if ( KeyDown!=null && ( wParam ==WM_KEYDOWN || wParam==WM_SYSKEYDOWN ))
239ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
240InBlock.gif                    Keys keyData=(Keys)MyKeyboardHookStruct.vkCode;
241InBlock.gif                    KeyEventArgs e = new KeyEventArgs(keyData);
242InBlock.gif                    KeyDown(this, e);
243ExpandedSubBlockEnd.gif                }

244InBlock.gif                
245InBlock.gif                // raise KeyPress
246InBlock.gif                if ( KeyPress!=null &&  wParam ==WM_KEYDOWN )
247ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
248InBlock.gif                    byte[] keyState = new byte[256];
249InBlock.gif                    GetKeyboardState(keyState);
250InBlock.gif
251InBlock.gif                    byte[] inBuffer= new byte[2];
252InBlock.gif                    if (ToAscii(MyKeyboardHookStruct.vkCode,
253InBlock.gif                            MyKeyboardHookStruct.scanCode,
254InBlock.gif                            keyState,
255InBlock.gif                            inBuffer,
256InBlock.gif                            MyKeyboardHookStruct.flags)==1
257ExpandedSubBlockStart.gifContractedSubBlock.gif                            dot.gif{
258InBlock.gif                                KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);
259InBlock.gif                                KeyPress(this, e);
260ExpandedSubBlockEnd.gif                            }

261ExpandedSubBlockEnd.gif                }

262InBlock.gif                
263InBlock.gif                // raise KeyUp
264InBlock.gif                if ( KeyUp!=null && ( wParam ==WM_KEYUP || wParam==WM_SYSKEYUP ))
265ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
266InBlock.gif                    Keys keyData=(Keys)MyKeyboardHookStruct.vkCode;
267InBlock.gif                    KeyEventArgs e = new KeyEventArgs(keyData);
268InBlock.gif                    KeyUp(this, e);
269ExpandedSubBlockEnd.gif                }

270InBlock.gif
271ExpandedSubBlockEnd.gif            }

272InBlock.gif            return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam); 
273ExpandedSubBlockEnd.gif        }

274ExpandedSubBlockEnd.gif    }

275ExpandedBlockEnd.gif}

276 None.gif

转载于:https://www.cnblogs.com/yuda/archive/2006/11/01/546418.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值