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

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

我们先新建一个类库GlobalMouseHook,

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

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

[c-sharp] view plain copy print ?
  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 plain copy print ?
  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. }  

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

Microsoft Visual Studio 2010做的C#实时监控鼠标位置和左键点击时的位置实例,主要代码: public class MouseHook { private Point point; private Point Point { get { return point; } set { if (point != value) { point = value; if (MouseMoveEvent != null) { var e = new MouseEventArgs(MouseButtons.None, 0, point.X, point.Y, 0); MouseMoveEvent(this, e); } } } } private int hHook; private const int WM_LBUTTONDOWN = 0x201; public const int WH_MOUSE_LL = 14; public Win32Api.HookProc hProc; public MouseHook() { this.Point = new Point(); } public int SetHook() { hProc = new Win32Api.HookProc(MouseHookProc); hHook = Win32Api.SetWindowsHookEx(WH_MOUSE_LL, hProc, IntPtr.Zero, 0); return hHook; } public void UnHook() { Win32Api.UnhookWindowsHookEx(hHook); } private int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) { Win32Api.MouseHookStruct MyMouseHookStruct = (Win32Api.MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(Win32Api.MouseHookStruct)); if (nCode < 0) { return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam); } else { if (MouseClickEvent != null) { MouseButtons button = MouseButtons.None; int clickCount = 0; switch ((Int32)wParam) { case WM_LBUTTONDOWN: button = MouseButtons.Left; clickCount = 1; break; } var e = new MouseEventArgs(button, clickCount, point.X, point.Y, 0); MouseClickEvent(this, e); } this.Point = new Point(MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y); return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam); } } public delegate void MouseMoveHandler(object sender, MouseEventArgs e); public event MouseMoveHandler MouseMoveEvent; public delegate void MouseClickHandler(object sender, MouseEventArgs e); public event MouseClickHandler MouseClickEvent; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值