美服疯狂坦克辅助瞄准外挂C#版开发(二)全局鼠标键盘HOOK

本文介绍如何使用C#开发全局鼠标键盘HOOK库,通过HOOK技术捕获和处理系统中的所有键盘鼠标事件。文章详细展示了鼠标键盘HOOK类的实现,包括键盘HOOK类、鼠标HOOK类以及HOOK抽象类,可用于游戏辅助或其他需要全局监听输入的场景。

大家都知道,Windows操作系统内部通讯是基于消息机制的。为了实现我们的功能,必须要能够截和处理获游戏中鼠标键盘事件的消息,常规做法是获取游戏窗体的句柄,然后加入HOOK,这样的好处是不会影响到其它正在运行的程序对鼠标键盘操作的响应。但是一般人在玩疯狂坦克的时候,应该不会同时运行Word之类的吧,也就是说,为了简单起见,我们在程序中加入的HOOK均为全局HOOK,注册到系统后会截获所有的键盘鼠标时间消息,而不管这个消息时由哪个程序激发,送往那个目标。

下面我们就用C#先写一个全局鼠标键盘HOOK库(部分代码及资料来源于CodeProject,具体URL找不到了,所以暂不列出):

HOOK抽象类 GlobalHook.cs

  1. using System;
  2. using System.Text;
  3. using System.Runtime.InteropServices;
  4. using System.Reflection;
  5. using System.Windows.Forms;
  6. namespace GlobalMouseKeyBoardHook
  7. {
  8.     /// <summary>
  9.     /// Abstract base class for Mouse and Keyboard hooks
  10.     /// </summary>
  11.     public abstract class GlobalHook
  12.     {
  13.         #region Windows API Code
  14.         [StructLayout(LayoutKind.Sequential)]
  15.         protected class POINT
  16.         {
  17.             public int x;
  18.             public int y;
  19.         }
  20.         [StructLayout(LayoutKind.Sequential)]
  21.         protected class MouseHookStruct
  22.         {
  23.             public POINT pt;
  24.             public int hwnd;
  25.             public int wHitTestCode;
  26.             public int dwExtraInfo;
  27.         }
  28.         [StructLayout(LayoutKind.Sequential)]
  29.         protected class MouseLLHookStruct
  30.         {
  31.             public POINT pt;
  32.             public int mouseData;
  33.             public int flags;
  34.             public int time;
  35.             public int dwExtraInfo;
  36.         }
  37.         [StructLayout(LayoutKind.Sequential)]
  38.         protected class KeyboardHookStruct
  39.         {
  40.             public int vkCode;
  41.             public int scanCode;
  42.             public int flags;
  43.             public int time;
  44.             public int dwExtraInfo;
  45.         }
  46.         /// <summary>
  47.         /// Extern Method:define Hook to Windows.
  48.         /// </summary>
  49.         /// <param name="idHook">Hook type,decide what message want to Hook</param>
  50.         /// <param name="lpfn">Function Pointer</param>
  51.         /// <param name="hMod">The dll or model include the Hook function</param>
  52.         /// <param name="dwThreadId">Correlative thread,if 0 means the global</param>
  53.         /// <returns>Hook id</returns>
  54.         [DllImport("user32.dll",CharSet = CharSet.Auto,CallingConvention = CallingConvention.StdCall,SetLastError = true)]
  55.         protected static extern int SetWindowsHookEx(int idHook,HookProc lpfn,IntPtr hMod,int dwThreadId);
  56.         /// <summary>
  57.         /// Extern Method:dispose the Hook.
  58.         /// </summary>
  59.         /// <param name="idHook">Hook id</param>
  60.         /// <returns>ture/false</returns>
  61.         [DllImport("user32.dll",CharSet = CharSet.Auto,CallingConvention = CallingConvention.StdCall,SetLastError = true)]
  62.         protected static extern bool UnhookWindowsHookEx(int idHook);
  63.         /// <summary>
  64.         /// Extern Method:call the next hook in the hook linked list
  65.         /// </summary>
  66.         /// <param name="idHook">this hook id</param>
  67.         /// <param name="nCode">the code contain the next hook need to do </param>
  68.         /// <param name="wParam">the parameters</param>
  69.         /// <param name="lParam">the parameters</param>
  70.         /// <returns>The value after the next hook finished.</returns>
  71.         [DllImport("user32.dll",CharSet = CharSet.Auto,CallingConvention = CallingConvention.StdCall)]
  72.         protected static extern int CallNextHookEx(int idHook,int nCode,int wParam,IntPtr lParam);
  73.         /// <summary>
  74.         /// Extern Method:transfer the virtual keycode and keyboard state to ascii string.
  75.         /// </summary>
  76.         /// <param name="uVirtKey">the virtual keycode need to transfer</param>
  77.         /// <param name="uScanCode">set the uVirtKey's transfer code</param>
  78.         /// <param name="lpbKeyState">256 length array to show all key's state in the keyboard</param>
  79.         /// <param name="lpwTransKey">the buffer of the transfer result</param>
  80.         /// <param name="fuState">define a menu is actived</param>
  81.         /// <returns>int</returns>
  82.         [DllImport("user32")]
  83.         protected static extern int ToAscii(int uVirtKey,int uScanCode,byte[] lpbKeyState,byte[] lpwTransKey,int fuState);
  84.         /// <summary>
  85.         /// Copy the 256 virtual key to he buffer
  86.         /// </summary>
  87.         /// <param name="pbKeyState">256 length array to show all key's state in the keyboard</param>
  88.         /// <returns>0</returns>
  89.         [DllImport("user32")]
  90.         protected static extern int GetKeyboardState(byte[] pbKeyState);
  91.         /// <summary>
  92.         /// get a virtual key's state
  93.         /// </summary>
  94.         /// <param name="vKey">a virtual key</param>
  95.         /// <returns>state</returns>
  96.         [DllImport("user32.dll",CharSet = CharSet.Auto,CallingConvention = CallingConvention.StdCall)]
  97.         protected static extern short GetKeyState(int vKey);
  98.         protected delegate int HookProc(int nCode,int wParam,IntPtr lParam);
  99.         protected const int WH_MOUSE_LL = 14;
  100.         protected const int WH_KEYBOARD_LL = 13;
  101.         protected const int WH_MOUSE = 7;
  102.         protected const int WH_KEYBOARD = 2;
  103.         protected const int WM_MOUSEMOVE = 0x200;
  104.         protected const int WM_LBUTTONDOWN = 0x201;
  105.         protected const int WM_RBUTTONDOWN = 0x204;
  106.         protected const int WM_MBUTTONDOWN = 0x207;
  107.         protected const int WM_LBUTTONUP = 0x202;
  108.         protected const int WM_RBUTTONUP = 0x205;
  109.         protected const int WM_MBUTTONUP = 0x208;
  110.         protected const int WM_LBUTTONDBLCLK = 0x203;
  111.         protected const int WM_RBUTTONDBLCLK = 0x206;
  112.         protected const int WM_MBUTTONDBLCLK = 0x209;
  113.         protected const int WM_MOUSEWHEEL = 0x020A;
  114.         protected const int WM_KEYDOWN = 0x100;
  115.         protected const int WM_KEYUP = 0x101;
  116.         protected const int WM_SYSKEYDOWN = 0x104;
  117.         protected const int WM_SYSKEYUP = 0x105;
  118.         protected const byte VK_SHIFT = 0x10;
  119.         protected const byte VK_CAPITAL = 0x14;
  120.         protected const byte VK_NUMLOCK = 0x90;
  121.         protected const byte VK_LSHIFT = 0xA0;
  122.         protected const byte VK_RSHIFT = 0xA1;
  123.         protected const byte VK_LCONTROL = 0xA2;
  124.         protected const byte VK_RCONTROL = 0x3;
  125.         protected const byte VK_LALT = 0xA4;
  126.         protected const byte VK_RALT = 0xA5;
  127.         protected const byte LLKHF_ALTDOWN = 0x20;
  128.         #endregion
  129.         #region Private Variables
  130.         protected int _hookType;
  131.         protected int _handleToHook;
  132.         protected bool _isStarted;
  133.         protected HookProc _hookCallback;
  134.         #endregion
  135.         #region Properties
  136.         public bool IsStarted
  137.         {
  138.             get
  139.             {
  140.                 return _isStarted;
  141.             }
  142.         }
  143.         #endregion
  144.         #region Constructor
  145.         public GlobalHook()
  146.         {
  147.             Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
  148.         }
  149.         #endregion
  150.         #region Methods
  151.         /// <summary>
  152.         /// start a hook
  153.         /// </summary>
  154.         public void Start()
  155.         {
  156.             if(!_isStarted && _hookType != 0)
  157.             {
  158.                 _hookCallback = new HookProc(HookCallbackProcedure);
  159.                 _handleToHook = SetWindowsHookEx(_hookType,_hookCallback,Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);
  160.                 if(_handleToHook != 0)
  161.                 {
  162.                     _isStarted = true;
  163.                 }
  164.             }
  165.         }
  166.         /// <summary>
  167.         /// stop the hook
  168.         /// </summary>
  169.         public void Stop()
  170.         {
  171.             if(_isStarted)
  172.             {
  173.                 UnhookWindowsHookEx(_handleToHook);
  174.                 _isStarted = false;
  175.             }
  176.         }
  177.         /// <summary>
  178.         /// virtual method:must be overriden by each extending hook
  179.         /// </summary>
  180.         /// <param name="nCode"></param>
  181.         /// <param name="wParam"></param>
  182.         /// <param name="lParam"></param>
  183.         /// <returns></returns>
  184.         protected virtual int HookCallbackProcedure(int nCode,Int32 wParam,IntPtr lParam)
  185.         {
  186.             return 0;
  187.         }
  188.         /// <summary>
  189.         /// stop the hook when the applaction is exiting.
  190.         /// </summary>
  191.         /// <param name="sender"></param>
  192.         /// <param name="e"></param>
  193.         protected void Application_ApplicationExit(object sender,EventArgs e)
  194.         {
  195.             if(_isStarted)
  196.             {
  197.                 Stop();
  198.             }
  199.         }
  200.         #endregion
  201.     }
  202. }

键盘HOOK类:KeyboardHook.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Windows.Forms;
  5. using System.Runtime.InteropServices;
  6. namespace GlobalMouseKeyBoardHook
  7. {
  8.     /// <summary>
  9.     /// Captures global keyboard events
  10.     /// </summary>
  11.     public class KeyboardHook : GlobalHook
  12.     {
  13.         public bool GoOnToCallNext = true;
  14.         #region Events
  15.         public event KeyEventHandler KeyDown;
  16.         public event KeyEventHandler KeyUp;
  17.         public event KeyPressEventHandler KeyPress;
  18.         #endregion
  19.         #region Constructor
  20.         public KeyboardHook()
  21.         {
  22.             _hookType = WH_KEYBOARD_LL;
  23.         }
  24.         #endregion
  25.         #region Methods
  26.         protected override int HookCallbackProcedure(int nCode, int wParam, IntPtr lParam)
  27.         {
  28.             bool handled = false;
  29.             if (nCode > -1 && (KeyDown != null || KeyUp != null || KeyPress != null))
  30.             {
  31.                 KeyboardHookStruct keyboardHookStruct =
  32.                     (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
  33.                 // Is Control being held down?
  34.                 bool control = ((GetKeyState(VK_LCONTROL) & 0x80) != 0) ||
  35.                                ((GetKeyState(VK_RCONTROL) & 0x80) != 0);
  36.                 // Is Shift being held down?
  37.                 bool shift = ((GetKeyState(VK_LSHIFT) & 0x80) != 0) ||
  38.                              ((GetKeyState(VK_RSHIFT) & 0x80) != 0);
  39.                 // Is Alt being held down?
  40.                 bool alt = ((GetKeyState(VK_LALT) & 0x80) != 0) ||
  41.                            ((GetKeyState(VK_RALT) & 0x80) != 0);
  42.                 // Is CapsLock on?
  43.                 bool capslock = (GetKeyState(VK_CAPITAL) != 0);
  44.                 // Create event using keycode and control/shift/alt values found above
  45.                 KeyEventArgs e = new KeyEventArgs(
  46.                     (Keys)(
  47.                         keyboardHookStruct.vkCode |
  48.                         (control ? (int)Keys.Control : 0) |
  49.                         (shift ? (int)Keys.Shift : 0) |
  50.                         (alt ? (int)Keys.Alt : 0)
  51.                         ));
  52.                 // Handle KeyDown and KeyUp events
  53.                 switch (wParam)
  54.                 {
  55.                     case WM_KEYDOWN:
  56.                     case WM_SYSKEYDOWN:
  57.                         if (KeyDown != null)
  58.                         {
  59.                             KeyDown(this, e);
  60.                             handled = handled || e.Handled;
  61.                         }
  62.                         break;
  63.                     case WM_KEYUP:
  64.                     case WM_SYSKEYUP:
  65.                         if (KeyUp != null)
  66.                         {
  67.                             KeyUp(this, e);
  68.                             handled = handled || e.Handled;
  69.                         }
  70.                         break;
  71.                 }
  72.                 // Handle KeyPress event
  73.                 if (wParam == WM_KEYDOWN &
  74.                    !handled &
  75.                    !e.SuppressKeyPress &
  76.                     KeyPress != null)
  77.                 {
  78.                     byte[] keyState = new byte[256];
  79.                     byte[] inBuffer = new byte[2];
  80.                     GetKeyboardState(keyState);
  81.                     if (ToAscii(keyboardHookStruct.vkCode,
  82.                               keyboardHookStruct.scanCode,
  83.                               keyState,
  84.                               inBuffer,
  85.                               keyboardHookStruct.flags) == 1)
  86.                     {
  87.                         char key = (char)inBuffer[0];
  88.                         if ((capslock ^ shift) && Char.IsLetter(key))
  89.                             key = Char.ToUpper(key);
  90.                         KeyPressEventArgs e2 = new KeyPressEventArgs(key);
  91.                         KeyPress(this, e2);
  92.                         handled = handled || e.Handled;
  93.                     }
  94.                 }
  95.             }
  96.             if(handled)
  97.             {
  98.                 return 1;
  99.             }
  100.             else
  101.             {
  102.                 if(GoOnToCallNext)
  103.                 {
  104.                     return CallNextHookEx(_handleToHook,nCode,wParam,lParam); 
  105.                 }
  106.                 else
  107.                 {
  108.                     return 1;
  109.                 }
  110.             }
  111.         }
  112.         #endregion
  113.     }
  114. }

鼠标HOOK类:MouseHook.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Windows.Forms;
  5. using System.Runtime.InteropServices;
  6. namespace GlobalMouseKeyBoardHook
  7. {
  8.     /// <summary>
  9.     /// Captures global mouse events
  10.     /// </summary>
  11.     public class MouseHook : GlobalHook
  12.     {
  13.         #region MouseEventType Enum
  14.         private enum MouseEventType
  15.         {
  16.             None,
  17.             MouseDown,
  18.             MouseUp,
  19.             DoubleClick,
  20.             MouseWheel,
  21.             MouseMove
  22.         }
  23.         #endregion
  24.         #region Events
  25.         public event MouseEventHandler MouseDown;
  26.         public event MouseEventHandler MouseUp;
  27.         public event MouseEventHandler MouseMove;
  28.         public event MouseEventHandler MouseWheel;
  29.         public event EventHandler Click;
  30.         public event EventHandler DoubleClick;
  31.         #endregion
  32.         #region Constructor
  33.         public MouseHook()
  34.         {
  35.             _hookType = WH_MOUSE_LL;
  36.         }
  37.         #endregion
  38.         #region Methods
  39.         protected override int HookCallbackProcedure(int nCode, int wParam, IntPtr lParam)
  40.         {
  41.             
  42.             if (nCode > -1 && (MouseDown != null || MouseUp != null || MouseMove != null))
  43.             {
  44.                 MouseLLHookStruct mouseHookStruct =
  45.                     (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));
  46.                 MouseButtons button = GetButton(wParam);
  47.                 MouseEventType eventType = GetEventType(wParam);
  48.                 MouseEventArgs e = new MouseEventArgs(
  49.                     button,
  50.                     (eventType == MouseEventType.DoubleClick ? 2 : 1),
  51.                     mouseHookStruct.pt.x,
  52.                     mouseHookStruct.pt.y,
  53.                     (eventType == MouseEventType.MouseWheel ? (int)((mouseHookStruct.mouseData >> 16) & 0xffff) : 0));
  54.                 // Prevent multiple Right Click events (this probably happens for popup menus)
  55.                 if (button == MouseButtons.Right && mouseHookStruct.flags != 0)
  56.                 {
  57.                     eventType = MouseEventType.None;
  58.                 }
  59.                 switch (eventType)
  60.                 {
  61.                     case MouseEventType.MouseDown:
  62.                         if (MouseDown != null)
  63.                         {
  64.                             MouseDown(this, e);
  65.                         }
  66.                         break;
  67.                     case MouseEventType.MouseUp:
  68.                         if (Click != null)
  69.                         {
  70.                             Click(thisnew EventArgs());
  71.                         }
  72.                         if (MouseUp != null)
  73.                         {
  74.                             MouseUp(this, e);
  75.                         }
  76.                         break;
  77.                     case MouseEventType.DoubleClick:
  78.                         if (DoubleClick != null)
  79.                         {
  80.                             DoubleClick(thisnew EventArgs());
  81.                         }
  82.                         break;
  83.                     case MouseEventType.MouseWheel:
  84.                         if (MouseWheel != null)
  85.                         {
  86.                             MouseWheel(this, e);
  87.                         }
  88.                         break;
  89.                     case MouseEventType.MouseMove:
  90.                         if (MouseMove != null)
  91.                         {
  92.                             MouseMove(this, e);
  93.                         }
  94.                         break;
  95.                     default:
  96.                         break;
  97.                 }
  98.             }
  99.             return CallNextHookEx(_handleToHook,nCode,wParam,lParam); 
  100.         }
  101.         private MouseButtons GetButton(Int32 wParam)
  102.         {
  103.             switch (wParam)
  104.             {
  105.                 case WM_LBUTTONDOWN:
  106.                 case WM_LBUTTONUP:
  107.                 case WM_LBUTTONDBLCLK:
  108.                     return MouseButtons.Left;
  109.                 case WM_RBUTTONDOWN:
  110.                 case WM_RBUTTONUP:
  111.                 case WM_RBUTTONDBLCLK:
  112.                     return MouseButtons.Right;
  113.                 case WM_MBUTTONDOWN:
  114.                 case WM_MBUTTONUP:
  115.                 case WM_MBUTTONDBLCLK:
  116.                     return MouseButtons.Middle;
  117.                 default:
  118.                     return MouseButtons.None;
  119.             }
  120.         }
  121.         private MouseEventType GetEventType(Int32 wParam)
  122.         {
  123.             switch (wParam)
  124.             {
  125.                 case WM_LBUTTONDOWN:
  126.                 case WM_RBUTTONDOWN:
  127.                 case WM_MBUTTONDOWN:
  128.                     return MouseEventType.MouseDown;
  129.                 case WM_LBUTTONUP:
  130.                 case WM_RBUTTONUP:
  131.                 case WM_MBUTTONUP:
  132.                     return MouseEventType.MouseUp;
  133.                 case WM_LBUTTONDBLCLK:
  134.                 case WM_RBUTTONDBLCLK:
  135.                 case WM_MBUTTONDBLCLK:
  136.                     return MouseEventType.DoubleClick;
  137.                 case WM_MOUSEWHEEL:
  138.                     return MouseEventType.MouseWheel;
  139.                 case WM_MOUSEMOVE:
  140.                     return MouseEventType.MouseMove;
  141.                 default:
  142.                     return MouseEventType.None;
  143.             }
  144.         }
  145.         #endregion
  146.         
  147.     }
  148. }

键盘模拟器:KeyboardSimulator.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Runtime.InteropServices;
  5. using System.Windows.Forms;
  6. namespace GlobalMouseKeyBoardHook
  7. {
  8.     /// <summary>
  9.     /// Standard Keyboard Shortcuts used by most applications
  10.     /// </summary>
  11.     public enum StandardShortcut
  12.     {
  13.         Copy,
  14.         Cut,
  15.         Paste,
  16.         SelectAll,
  17.         Save,
  18.         Open,
  19.         New,
  20.         Close,
  21.         Print
  22.     }
  23.     /// <summary>
  24.     /// Simulate keyboard key presses
  25.     /// </summary>
  26.     public static class KeyboardSimulator
  27.     {
  28.         #region Windows API Code
  29.         const int KEYEVENTF_EXTENDEDKEY = 0x1;
  30.         const int KEYEVENTF_KEYUP = 0x2;
  31.         [DllImport("user32.dll")]
  32.         static extern void keybd_event(byte key, byte scan, int flags, int extraInfo);
  33.         //[DllImport("user32.dll")]
  34.         //static extern int SetKeyboardState(byte[] lpKeyState);
  35.         //[DllImport("user32.dll")]
  36.         //static extern int GetKeyboardState(byte[] lpKeyState);
  37.         #endregion
  38.         #region Methods
  39.         public static void KeyDown(Keys key)
  40.         {
  41.             keybd_event(ParseKey(key), 0, 0, 0);
  42.         }
  43.         public static void KeyUp(Keys key)
  44.         {
  45.             keybd_event(ParseKey(key), 0, KEYEVENTF_KEYUP, 0);
  46.         }
  47.         public static void KeyPress(Keys key)
  48.         {
  49.             KeyDown(key);
  50.             KeyUp(key);
  51.         }
  52.         //public static void KeyHold(Keys key)
  53.         //{
  54.         //    byte[] KeyBoardState = new byte[256];
  55.         //    GetKeyboardState(KeyBoardState);
  56.         //    KeyBoardState[ParseKey(key)] =1;
  57.         //    SetKeyboardState(KeyBoardState);
  58.         //}
  59.         public static void SimulateStandardShortcut(StandardShortcut shortcut)
  60.         {
  61.             switch (shortcut)
  62.             {
  63.                 case StandardShortcut.Copy:
  64.                     KeyDown(Keys.Control);
  65.                     KeyPress(Keys.C);
  66.                     KeyUp(Keys.Control);
  67.                     break;
  68.                 case StandardShortcut.Cut:
  69.                     KeyDown(Keys.Control);
  70.                     KeyPress(Keys.X);
  71.                     KeyUp(Keys.Control);
  72.                     break;
  73.                 case StandardShortcut.Paste:
  74.                     KeyDown(Keys.Control);
  75.                     KeyPress(Keys.V);
  76.                     KeyUp(Keys.Control);
  77.                     break;
  78.                 case StandardShortcut.SelectAll:
  79.                     KeyDown(Keys.Control);
  80.                     KeyPress(Keys.A);
  81.                     KeyUp(Keys.Control);
  82.                     break;
  83.                 case StandardShortcut.Save:
  84.                     KeyDown(Keys.Control);
  85.                     KeyPress(Keys.S);
  86.                     KeyUp(Keys.Control);
  87.                     break;
  88.                 case StandardShortcut.Open:
  89.                     KeyDown(Keys.Control);
  90.                     KeyPress(Keys.O);
  91.                     KeyUp(Keys.Control);
  92.                     break;
  93.                 case StandardShortcut.New:
  94.                     KeyDown(Keys.Control);
  95.                     KeyPress(Keys.N);
  96.                     KeyUp(Keys.Control);
  97.                     break;
  98.                 case StandardShortcut.Close:
  99.                     KeyDown(Keys.Alt);
  100.                     KeyPress(Keys.F4);
  101.                     KeyUp(Keys.Alt);
  102.                     break;
  103.                 case StandardShortcut.Print:
  104.                     KeyDown(Keys.Control);
  105.                     KeyPress(Keys.P);
  106.                     KeyUp(Keys.Control);
  107.                     break;
  108.             }
  109.         }
  110.         static byte ParseKey(Keys key)
  111.         {
  112.             // Alt, Shift, and Control need to be changed for API function to work with them
  113.             switch (key)
  114.             {
  115.                 case Keys.Alt:
  116.                     return (byte)18;
  117.                 case Keys.Control:
  118.                     return (byte)17;
  119.                 case Keys.Shift:
  120.                     return (byte)16;
  121.                 default:
  122.                     return (byte)key;
  123.             }
  124.         } 
  125.         #endregion
  126.     }
  127. }

鼠标模拟器:MouseSimulator.cs

  1. using System;
  2. using System.Text;
  3. using System.Runtime.InteropServices;
  4. using System.Drawing;
  5. using System.Windows.Forms;
  6. namespace GlobalMouseKeyBoardHook
  7. {
  8.     /// <summary>
  9.     /// Mouse buttons that can be pressed
  10.     /// </summary>
  11.     public enum MouseButton
  12.     {
  13.         Left = 0x2,
  14.         Right = 0x8,
  15.         Middle = 0x20
  16.     }
  17.     /// <summary>
  18.     /// Operations that simulate mouse events
  19.     /// </summary>
  20.     public static class MouseSimulator
  21.     {
  22.         #region Windows API Code
  23.         [DllImport("user32.dll")]
  24.         static extern int ShowCursor(bool show);
  25.         [DllImport("user32.dll")]
  26.         static extern void mouse_event(int flags, int dX, int dY, int buttons, int extraInfo);
  27.         const int MOUSEEVENTF_MOVE = 0x1;
  28.         const int MOUSEEVENTF_LEFTDOWN = 0x2;
  29.         const int MOUSEEVENTF_LEFTUP = 0x4;
  30.         const int MOUSEEVENTF_RIGHTDOWN = 0x8;
  31.         const int MOUSEEVENTF_RIGHTUP = 0x10;
  32.         const int MOUSEEVENTF_MIDDLEDOWN = 0x20;
  33.         const int MOUSEEVENTF_MIDDLEUP = 0x40;
  34.         const int MOUSEEVENTF_WHEEL = 0x800;
  35.         const int MOUSEEVENTF_ABSOLUTE = 0x8000; 
  36.         #endregion
  37.         #region Properties
  38.         /// <summary>
  39.         /// Gets or sets a structure that represents both X and Y mouse coordinates
  40.         /// </summary>
  41.         public static Point Position
  42.         {
  43.             get
  44.             {
  45.                 return new Point(Cursor.Position.X, Cursor.Position.Y);
  46.             }
  47.             set
  48.             {
  49.                 Cursor.Position = value;
  50.             }
  51.         }
  52.         /// <summary>
  53.         /// Gets or sets only the mouse's x coordinate
  54.         /// </summary>
  55.         public static int X
  56.         {
  57.             get
  58.             {
  59.                 return Cursor.Position.X;
  60.             }
  61.             set
  62.             {
  63.                 Cursor.Position = new Point(value, Y);
  64.             }
  65.         }
  66.         /// <summary>
  67.         /// Gets or sets only the mouse's y coordinate
  68.         /// </summary>
  69.         public static int Y
  70.         {
  71.             get
  72.             {
  73.                 return Cursor.Position.Y;
  74.             }
  75.             set
  76.             {
  77.                 Cursor.Position = new Point(X, value);
  78.             }
  79.         } 
  80.         #endregion
  81.         #region Methods
  82.         /// <summary>
  83.         /// Press a mouse button down
  84.         /// </summary>
  85.         /// <param name="button"></param>
  86.         public static void MouseDown(MouseButton button)
  87.         {
  88.             mouse_event(((int)button), 0, 0, 0, 0);
  89.         }
  90.         /// <summary>
  91.         /// Press a mouse button down
  92.         /// </summary>
  93.         /// <param name="button"></param>
  94.         public static void MouseDown(MouseButtons button)
  95.         {
  96.             switch (button)
  97.             {
  98.                 case MouseButtons.Left:
  99.                     MouseDown(MouseButton.Left);
  100.                     break;
  101.                 case MouseButtons.Middle:
  102.                     MouseDown(MouseButton.Middle);
  103.                     break;
  104.                 case MouseButtons.Right:
  105.                     MouseDown(MouseButton.Right);
  106.                     break;
  107.             }
  108.         }
  109.         /// <summary>
  110.         /// Let a mouse button up
  111.         /// </summary>
  112.         /// <param name="button"></param>
  113.         public static void MouseUp(MouseButton button)
  114.         {
  115.             mouse_event(((int)button) * 2, 0, 0, 0, 0);
  116.         }
  117.         /// <summary>
  118.         /// Let a mouse button up
  119.         /// </summary>
  120.         /// <param name="button"></param>
  121.         public static void MouseUp(MouseButtons button)
  122.         {
  123.             switch (button)
  124.             {
  125.                 case MouseButtons.Left:
  126.                     MouseUp(MouseButton.Left);
  127.                     break;
  128.                 case MouseButtons.Middle:
  129.                     MouseUp(MouseButton.Middle);
  130.                     break;
  131.                 case MouseButtons.Right:
  132.                     MouseUp(MouseButton.Right);
  133.                     break;
  134.             }
  135.         }
  136.         /// <summary>
  137.         /// Click a mouse button (down then up)
  138.         /// </summary>
  139.         /// <param name="button"></param>
  140.         public static void Click(MouseButton button)
  141.         {
  142.             MouseDown(button);
  143.             MouseUp(button);
  144.         }
  145.         /// <summary>
  146.         /// Click a mouse button (down then up)
  147.         /// </summary>
  148.         /// <param name="button"></param>
  149.         public static void Click(MouseButtons button)
  150.         {
  151.             switch (button)
  152.             {
  153.                 case MouseButtons.Left:
  154.                     Click(MouseButton.Left);
  155.                     break;
  156.                 case MouseButtons.Middle:
  157.                     Click(MouseButton.Middle);
  158.                     break;
  159.                 case MouseButtons.Right:
  160.                     Click(MouseButton.Right);
  161.                     break;
  162.             }
  163.         }
  164.         /// <summary>
  165.         /// Double click a mouse button (down then up twice)
  166.         /// </summary>
  167.         /// <param name="button"></param>
  168.         public static void DoubleClick(MouseButton button)
  169.         {
  170.             Click(button);
  171.             Click(button);
  172.         }
  173.         /// <summary>
  174.         /// Double click a mouse button (down then up twice)
  175.         /// </summary>
  176.         /// <param name="button"></param>
  177.         public static void DoubleClick(MouseButtons button)
  178.         {
  179.             switch (button)
  180.             {
  181.                 case MouseButtons.Left:
  182.                     DoubleClick(MouseButton.Left);
  183.                     break;
  184.                 case MouseButtons.Middle:
  185.                     DoubleClick(MouseButton.Middle);
  186.                     break;
  187.                 case MouseButtons.Right:
  188.                     DoubleClick(MouseButton.Right);
  189.                     break;
  190.             }
  191.         }
  192.         /// <summary>
  193.         /// Roll the mouse wheel. Delta of 120 wheels up once normally, -120 wheels down once normally
  194.         /// </summary>
  195.         /// <param name="delta"></param>
  196.         public static void MouseWheel(int delta)
  197.         {
  198.             mouse_event(MOUSEEVENTF_WHEEL, 0, 0, delta, 0);
  199.         }
  200.         /// <summary>
  201.         /// Show a hidden current on currently application
  202.         /// </summary>
  203.         public static void Show()
  204.         {
  205.             ShowCursor(true);
  206.         }
  207.         /// <summary>
  208.         /// Hide mouse cursor only on current application's forms
  209.         /// </summary>
  210.         public static void Hide()
  211.         {
  212.             ShowCursor(false);
  213.         } 
  214.         #endregion
  215.     }
  216. }

至此,我们的全局鼠标键盘HOOK库所有源代码已经完成,直接编译输出为GlobalMouseKeyBoardHook.dll即可在其它任何需要全局HOOK的程序中直接引用。

 

调用DEMO:

1、在新建的WinFrom项目中引用GlobalMouseKeyBoardHook.dll。

2、Form1.cs中替换以下代码,直接编译运行。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using GlobalMouseKeyBoardHook;
  9. namespace WindowsApplication2
  10. {
  11.     public partial class Form1:Form
  12.     {
  13.         public Form1()
  14.         {
  15.             InitializeComponent();
  16.         }
  17.         private void Form1_Load(object sender,EventArgs e)
  18.         {
  19.             MouseHook MH = new MouseHook();
  20.             KeyboardHook KH = new KeyboardHook();
  21.             MH.MouseDown += new MouseEventHandler(MouseHook_MouseDown);
  22.             MH.MouseUp += new MouseEventHandler(MouseHook_MouseUp);
  23.             KH.KeyDown += new KeyEventHandler(KeyBoardHook_KeyDown);
  24.             KH.KeyUp += new KeyEventHandler(KeyBoardHook_KeyUp);
  25.             KH.KeyPress += new KeyPressEventHandler(KeyBoardHook_KeyPress);
  26.             MH.Start();
  27.             KH.Start();
  28.         }
  29.         private void MouseHook_MouseDown(object sender,MouseEventArgs e)
  30.         {
  31.             MessageBox.Show("当前鼠标鼠标:" + e.X.ToString() + "," + e.Y.ToString());
  32.         }
  33.         private void MouseHook_MouseUp(object sender,MouseEventArgs e)
  34.         {
  35.             MessageBox.Show("当前鼠标鼠标:" + e.X.ToString() + "," + e.Y.ToString());
  36.         }
  37.         private void KeyBoardHook_KeyDown(object sender,KeyEventArgs e)
  38.         {
  39.             MessageBox.Show(e.KeyCode.ToString());
  40.         }
  41.         private void KeyBoardHook_KeyUp(object sender,KeyEventArgs e)
  42.         {
  43.             MessageBox.Show(e.KeyCode.ToString());
  44.         }
  45.         private void KeyBoardHook_KeyPress(object sender,KeyPressEventArgs e)
  46.         {
  47.             MessageBox.Show(e.KeyChar.ToString());
  48.         }
  49.     }
  50. }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值