【问题标题】:How to Set mouse cursor position to a specified point on screen in C#?如何在 C# 中将鼠标光标位置设置到屏幕上的指定点?
【发布时间】:2022-01-16 09:26:34
【问题描述】:

如何在C#中将鼠标光标位置设置到屏幕上的指定点?

我必须破解接收鼠标和键盘坐标并按下的主板缓冲区吗???

还有其他人可以点击吗?或者我想象一下???

【问题讨论】:

  • 立即想到的问题是“为什么”?
  • 在我的脑海里做点什么。为什么?
  • @MatthewScharley 我来这里是为了“自动化”..

标签: c# automation mouse click


【解决方案1】:

下面会设置鼠标位置并执行点击:

public static void ClickSomePoint() {
    // Set the cursor position
    System.Windows.Forms.Cursor.Position = new Point(20, 35);

    DoClickMouse(0x2); // Left mouse button down
    DoClickMouse(0x4); // Left mouse button up
}   

static void DoClickMouse(int mouseButton) {
    var input = new INPUT() {
        dwType = 0, // Mouse input
        mi = new MOUSEINPUT() { dwFlags = mouseButton }
    };

    if (SendInput(1, input, Marshal.SizeOf(input)) == 0) { 
        throw new Exception();
    }
}
[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT {
    int dx;
    int dy;
    int mouseData;
    public int dwFlags;
    int time;
    IntPtr dwExtraInfo;
}   
struct INPUT {
    public uint dwType;
    public MOUSEINPUT mi;
}   
[DllImport("user32.dll", SetLastError=true)]
static extern uint SendInput(uint cInputs, INPUT input, int size);

请记住,这可能会让用户非常烦人。

:)


如果您想点击表单上的按钮,可以使用'PerformClick()' 方法。

【讨论】:

  • 但是如果我想点击屏幕上的任何东西,有什么可以做的,否则我的想象力会到此结束?
  • 每次都会发生 if 范围内的异常。我能做什么?
  • 记住SendInput的第二个参数应该是ref,否则签名不匹配,你会得到一个PInvoke异常!
【解决方案2】:

在 Windows 10 中获取和设置鼠标位置:

在 c# .NET Framework 4.0 中使用 Cursor.Position 属性要简单得多

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.cursor.position?view=netcore-3.1

    public static void ClickSomePoint()
    {

        // get mouse position
        System.Drawing.Point screenPos = System.Windows.Forms.Cursor.Position;

        // create X,Y point (0,0) explicitly with System.Drawing 
        System.Drawing.Point leftTop = new System.Drawing.Point(0,0);

        // set mouse position
        Cursor.Position = leftTop; 
        Console.WriteLine(screenPos);
    }

【讨论】:

    【解决方案3】:

    最简单的鼠标定位方式:

    左零为左,右零为上位(您可以将其更改为您想要的任何数字)(要使用此代码,您需要使用using System.Drawingusing System.Windows.Forms命名空间)

    Cursor.Position = new Point(0,0);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多