C#实时获取鼠标坐标及模拟鼠标点击

在 C# 中,你可以使用 System.Windows.FormsSystem.Drawing 命名空间来实时获取鼠标坐标,并使用 System.Windows.Forms.Cursoruser32.dll 来模拟鼠标点击。以下是完整的实现方法:

图片[1]_C#实时获取鼠标坐标及模拟鼠标点击_知途无界

1. 实时获取鼠标坐标

方法 1:使用 Cursor.Position(Windows Forms)

using System;
using System.Drawing;
using System.Windows.Forms;

class MouseTracker
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Form form = new Form
        {
            Text = "鼠标坐标跟踪",
            Width = 300,
            Height = 200
        };

        Label label = new Label
        {
            AutoSize = true,
            Location = new Point(10, 10),
            Text = "移动鼠标查看坐标..."
        };

        form.MouseMove += (sender, e) =>
        {
            label.Text = $"X: {e.X}, Y: {e.Y}"; // 相对于窗体的坐标
        };

        // 获取全局鼠标坐标(相对于屏幕)
        Timer timer = new Timer { Interval = 100 };
        timer.Tick += (sender, e) =>
        {
            Point globalPos = Cursor.Position;
            label.Text = $"全局坐标: X: {globalPos.X}, Y: {globalPos.Y}";
        };
        timer.Start();

        form.ShowDialog();
    }
}

说明

  • Cursor.Position 返回全局鼠标坐标(相对于屏幕)。
  • MouseMove 事件返回相对于窗体的坐标。

方法 2:使用 GetCursorPos(Win32 API)

如果需要在控制台程序或非 UI 环境下获取鼠标坐标,可以使用 user32.dllGetCursorPos 函数:

using System;
using System.Runtime.InteropServices;

class MouseTracker
{
    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int X;
        public int Y;
    }

    [DllImport("user32.dll")]
    public static extern bool GetCursorPos(out POINT lpPoint);

    static void Main()
    {
        while (true)
        {
            if (GetCursorPos(out POINT point))
            {
                Console.Clear();
                Console.WriteLine($"X: {point.X}, Y: {point.Y}");
            }
            System.Threading.Thread.Sleep(100); // 每 100ms 更新一次
        }
    }
}

说明

  • GetCursorPos 返回全局鼠标坐标(相对于屏幕)。
  • 适用于控制台程序或后台服务。

2. 模拟鼠标点击

方法 1:使用 mouse_event(Win32 API)

using System;
using System.Runtime.InteropServices;

class MouseSimulator
{
    [DllImport("user32.dll")]
    public static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, UIntPtr dwExtraInfo);

    // 鼠标事件常量
    private const uint MOUSEEVENTF_LEFTDOWN = 0x0002; // 左键按下
    private const uint MOUSEEVENTF_LEFTUP = 0x0004;   // 左键释放
    private const uint MOUSEEVENTF_RIGHTDOWN = 0x0008; // 右键按下
    private const uint MOUSEEVENTF_RIGHTUP = 0x0010;   // 右键释放

    static void Main()
    {
        // 模拟左键点击(屏幕坐标 100, 100)
        int x = 100, y = 100;
        Cursor.Position = new System.Drawing.Point(x, y); // 移动鼠标到指定位置

        mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, UIntPtr.Zero); // 按下
        mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, UIntPtr.Zero);     // 释放
    }
}

说明

  • mouse_event 可以模拟鼠标点击、移动等操作。
  • 需要先移动鼠标到目标位置(Cursor.Position)。

方法 2:使用 SendInput(更现代的方式)

mouse_event 在较新版本的 Windows 中已被标记为过时,推荐使用 SendInput

using System;
using System.Runtime.InteropServices;

class MouseSimulator
{
    [StructLayout(LayoutKind.Sequential)]
    struct INPUT
    {
        public uint type;
        public MOUSEINPUT mi;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct MOUSEINPUT
    {
        public int dx;
        public int dy;
        public uint mouseData;
        public uint dwFlags;
        public uint time;
        public IntPtr dwExtraInfo;
    }

    private const uint INPUT_MOUSE = 0;
    private const uint MOUSEEVENTF_MOVE = 0x0001; // 移动鼠标
    private const uint MOUSEEVENTF_LEFTDOWN = 0x0002; // 左键按下
    private const uint MOUSEEVENTF_LEFTUP = 0x0004;   // 左键释放
    private const uint MOUSEEVENTF_RIGHTDOWN = 0x0008; // 右键按下
    private const uint MOUSEEVENTF_RIGHTUP = 0x0010;   // 右键释放
    private const uint MOUSEEVENTF_ABSOLUTE = 0x8000; // 绝对坐标

    [DllImport("user32.dll")]
    private static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);

    static void Main()
    {
        // 模拟左键点击(屏幕坐标 100, 100)
        int x = 100 * 65535 / System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width; // 转换为绝对坐标
        int y = 100 * 65535 / System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;

        INPUT[] inputs = new INPUT[4];

        // 移动鼠标到 (100, 100)
        inputs[0].type = INPUT_MOUSE;
        inputs[0].mi = new MOUSEINPUT { dx = x, dy = y, dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE };

        // 左键按下
        inputs[1].type = INPUT_MOUSE;
        inputs[1].mi = new MOUSEINPUT { dwFlags = MOUSEEVENTF_LEFTDOWN };

        // 左键释放
        inputs[2].type = INPUT_MOUSE;
        inputs[2].mi = new MOUSEINPUT { dwFlags = MOUSEEVENTF_LEFTUP };

        // 发送输入
        SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
    }
}

说明

  • SendInput 是更现代的方式,支持绝对坐标(MOUSEEVENTF_ABSOLUTE)。
  • 需要将坐标转换为 [0, 65535] 范围(屏幕的相对位置)。

总结

功能方法适用场景
获取鼠标坐标Cursor.PositionWindows Forms
获取鼠标坐标GetCursorPos控制台/后台
模拟鼠标点击mouse_event简单点击(旧版)
模拟鼠标点击SendInput现代方式(推荐)

如果你需要在 控制台程序 中获取鼠标坐标并模拟点击,推荐使用 GetCursorPos + SendInput
如果你在 Windows Forms/WPF 中操作,可以直接用 Cursor.Positionmouse_event

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞6 分享
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容