首页 > 代码库 > 使用c#创建一个可以监视全局鼠标位置的程序

使用c#创建一个可以监视全局鼠标位置的程序

首先要在焦点不在当前应用程序中也要获得鼠标位置,我们就需要使用全局鼠标钩子

我们先新建一个类库GlobalMouseHook,

然后导入命名空间:System.Windows.Forms;
System.Runtime.InteropServices;

将类重命名为MouseHook,其代码如下:

 

[c-sharp] view plaincopy
 
  1. using System.Windows.Forms;  
  2. using System.Runtime.InteropServices;  
  3.   
  4. namespace GlobalMouseHook  
  5. {  
  6.     public class MouseHook  
  7.     {  
  8.         private const int WM_MOUSEMOVE = 0x200;  
  9.         private const int WM_LBUTTONDOWN = 0x201;  
  10.         private const int WM_RBUTTONDOWN = 0x204;  
  11.         private const int WM_MBUTTONDOWN = 0x207;  
  12.         private const int WM_LBUTTONUP = 0x202;  
  13.         private const int WM_RBUTTONUP = 0x205;  
  14.         private const int WM_MBUTTONUP = 0x208;  
  15.         private const int WM_LBUTTONDBLCLK = 0x203;  
  16.         private const int WM_RBUTTONDBLCLK = 0x206;  
  17.         private const int WM_MBUTTONDBLCLK = 0x209;  
  18.   
  19.         //全局的事件  
  20.         public event MouseEventHandler OnMouseActivity;  
  21.   
  22.         static int hMouseHook = 0; //鼠标钩子句柄  
  23.   
  24.         //鼠标常量  
  25.         public const int WH_MOUSE_LL  = 14; //mouse hook constant  
  26.   
  27.         HookProc MouseHookProcedure; //声明鼠标钩子事件类型.  
  28.   
  29.         //声明一个Point的封送类型  
  30.         [StructLayout(LayoutKind.Sequential)]  
  31.         public class POINT   
  32.         {  
  33.             public int x;  
  34.             public int y;  
  35.         }  
  36.   
  37.         //声明鼠标钩子的封送结构类型  
  38.         [StructLayout(LayoutKind.Sequential)]  
  39.         public class MouseHookStruct   
  40.         {  
  41.             public POINT pt;  
  42.             public int hWnd;  
  43.             public int wHitTestCode;  
  44.             public int dwExtraInfo;  
  45.         }  
  46.   
  47.         //装置钩子的函数  
  48.         [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]  
  49.         public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);  
  50.   
  51.         //卸下钩子的函数  
  52.         [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]  
  53.         public static extern bool UnhookWindowsHookEx(int idHook);  
  54.   
  55.         //下一个钩挂的函数  
  56.         [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]  
  57.         public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);    
  58.   
  59.         public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);  
  60.   
  61.         /// <summary>  
  62.         /// 墨认的构造函数构造当前类的实例.  
  63.         /// </summary>  
  64.         public MouseHook()   
  65.         {  
  66.         }  
  67.   
  68.         //析构函数.  
  69.         ~MouseHook()   
  70.         {   
  71.         Stop();  
  72.         }   
  73.   
  74.         public void Start()  
  75.         {  
  76.             //安装鼠标钩子  
  77.             if(hMouseHook == 0)  
  78.             {  
  79.                 //生成一个HookProc的实例.  
  80.                 MouseHookProcedure = new HookProc(MouseHookProc);  
  81.   
  82.                 hMouseHook = SetWindowsHookEx( WH_MOUSE_LL, MouseHookProcedure, Marshal.GetHINSTANCE(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]), 0);  
  83.   
  84.                 //如果装置失败停止钩子  
  85.                 if(hMouseHook == 0 )   
  86.                 {  
  87.                     Stop();  
  88.                     throw new Exception("SetWindowsHookEx failed.");  
  89.                 }  
  90.             }  
  91.         }  
  92.   
  93.         public void Stop()  
  94.         {  
  95.             bool retMouse =true;  
  96.             if(hMouseHook != 0)  
  97.             {  
  98.                 retMouse = UnhookWindowsHookEx(hMouseHook);  
  99.                 hMouseHook = 0;  
  100.             }   
  101.   
  102.             //如果卸下钩子失败  
  103.             if (!(retMouse)) throw new Exception("UnhookWindowsHookEx failed.");  
  104.         }  
  105.   
  106.         private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)  
  107.         {  
  108.             //如果正常运行并且用户要监听鼠标的消息  
  109.             if ((nCode >= 0) && (OnMouseActivity!=null))   
  110.             {   
  111.                 MouseButtons button=MouseButtons.None;  
  112.                 int clickCount=0;  
  113.   
  114.                 switch (wParam)  
  115.                 {  
  116.                 case WM_LBUTTONDOWN:   
  117.                 button=MouseButtons.Left;   
  118.                 clickCount=1;  
  119.                 break;  
  120.                 case WM_LBUTTONUP:   
  121.                 button=MouseButtons.Left;   
  122.                 clickCount=1;  
  123.                 break;  
  124.                 case WM_LBUTTONDBLCLK:   
  125.                 button=MouseButtons.Left;   
  126.                 clickCount=2;  
  127.                 break;  
  128.                 case WM_RBUTTONDOWN:   
  129.                 button=MouseButtons.Right;   
  130.                 clickCount=1;  
  131.                 break;  
  132.                 case WM_RBUTTONUP:   
  133.                 button=MouseButtons.Right;   
  134.                 clickCount=1;  
  135.                 break;  
  136.                 case WM_RBUTTONDBLCLK:   
  137.                 button=MouseButtons.Right;   
  138.                 clickCount=2;  
  139.                 break;  
  140.             }  
  141.   
  142.             //从回调函数中得到鼠标的信息  
  143.             MouseHookStruct MyMouseHookStruct = (MouseHookStruct) Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));  
  144.             MouseEventArgs e=new MouseEventArgs(button, clickCount, MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y, 0 );  
  145.             //if(e.X>700)return 1;//如果想要限制鼠标在屏幕中的移动区域可以在此处设置  
  146.             OnMouseActivity(this, e);  
  147.         }  
  148.         return CallNextHookEx(hMouseHook, nCode, wParam, lParam);   
  149.         }  
  150.     }  
  151. }  

 

这样就创建了一个全局的鼠标钩子,我们只需要在其它地方引用 这个dll就可以了

使用示例:

 

[c-sharp] view plaincopy
 
  1. public partial class Form1 : Form  
  2. {  
  3.     MouseHook mouse = new MouseHook();  
  4.     public Form1()  
  5.     {  
  6.         InitializeComponent();  
  7.         mouse.OnMouseActivity += new MouseEventHandler(mouse_OnMouseActivity);  
  8.         mouse.Start();  
  9.     }  
  10.   
  11.     void mouse_OnMouseActivity(object sender, MouseEventArgs e)  
  12.     {  
  13.         string str = "X:" + e.X + "  Y:" + e.Y;  
  14.         this.Text = str;  
  15.     }  
  16. }  

 

这样这个窗体都可以在全局状态下显示鼠标的位置了,不管你焦点在哪,也不管你焦点是否在当前窗体上

使用c#创建一个可以监视全局鼠标位置的程序