C# 设置鼠标光标位置
1using System.Drawing; 2using System.Runtime.InteropServices; 3 4namespace ZB.QueueSys.Common 5{ 6 public class MouseHelper 7 { 8 private static MouseHelper instance; 9 public static MouseHelper Instance 10 { 11 get 12 { 13 if (instance == null) instance = new MouseHelper(); 14 return MouseHelper.instance; 15 } 16 } 17 18 /// <summary> 19 /// 引用user32.dll动态链接库(windows api), 20 /// 使用库中定义 API:SetCursorPos 21 /// </summary> 22 [DllImport("user32.dll")] 23 private static extern int SetCursorPos(int x, int y); 24 /// <summary> 25 /// 移动鼠标到指定的坐标点 26 /// </summary> 27 public void MoveMouseToPoint(Point p) 28 { 29 SetCursorPos(p.X, p.Y); 30 } 31 /// <summary> 32 /// 设置鼠标的移动范围 33 /// </summary> 34 public void SetMouseRectangle(Rectangle rectangle) 35 { 36 System.Windows.Forms.Cursor.Clip = rectangle; 37 } 38 /// <summary> 39 /// 设置鼠标位于屏幕中心 40 /// </summary> 41 public void SetMouseAtCenterScreen() 42 { 43 int winHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height; 44 int winWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width; 45 Point centerP = new Point(winWidth / 2, winHeight / 2); 46 MoveMouseToPoint(centerP); 47 } 48 49 } 50} 51 52 53调用测试如下: 54 int y = Screen.PrimaryScreen.WorkingArea.Height - 180; 55 int x = Screen.PrimaryScreen.WorkingArea.Width - 180; 56 Point p = new Point(x, y); 57 MouseHelper.Instance.MoveMouseToPoint(p);
C#获取指定控件所在屏幕的位置
1 int x = this.dgvList.Location.X; 2 int y = this.dgvList.Location.Y; 3 Point p = new Point(x, y); 4 Point pp = this.dgvList.PointToScreen(p); 5 MouseHelper.Instance.MoveMouseToPoint(pp);