C# 实现模拟控制鼠标点击事件
/// <summary> /// 引用user32.dll动态链接库(windows api), /// 使用库中定义 API:SetCursorPos /// </summary> [DllImport("user32.dll")] private static extern int SetCursorPos(int x, int y); /// <summary> /// 移动鼠标到指定的坐标点 /// </summary> public void MoveMouseToPoint(Point p) { SetCursorPos(p.X, p.Y); } /// <summary> /// 设置鼠标的移动范围 /// </summary> public void SetMouseRectangle(Rectangle rectangle) { System.Windows.Forms.Cursor.Clip = rectangle; } /// <summary> /// 设置鼠标位于屏幕中心 /// </summary> public void SetMouseAtCenterScreen() { //当前屏幕的宽高 int winHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height; int winWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width; //设置鼠标的x,y位置 loginx = winWidth / 2; loginy = winHeight / 2; Point centerP = new Point(loginx, loginy); //移动鼠标 MoveMouseToPoint(centerP); } //点击事件 [DllImport("User32")] //下面这一行对应着下面的点击事件 // public extern static void mouse_event(int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo); public extern static void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); public const int MOUSEEVENTF_LEFTDOWN = 0x2; public const int MOUSEEVENTF_LEFTUP = 0x4; public enum MouseEventFlags { Move = 0x0001, //移动鼠标 LeftDown = 0x0002,//模拟鼠标左键按下 LeftUp = 0x0004,//模拟鼠标左键抬起 RightDown = 0x0008,//鼠标右键按下 RightUp = 0x0010,//鼠标右键抬起 MiddleDown = 0x0020,//鼠标中键按下 MiddleUp = 0x0040,//中键抬起 Wheel = 0x0800, Absolute = 0x8000//标示是否采用绝对坐标 } //鼠标将要到的x,y位置 public static int loginx, loginy; private void button1_Click(object sender, EventArgs e) { SetMouseAtCenterScreen();//模拟鼠标移动到指定坐标 mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, loginx, loginy, 0, 0);//模拟鼠标点击 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!