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

10

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

我必须入侵接收鼠标和键盘坐标和按键的主板缓冲区吗?

还有其他方法可以进行点击操作,还是我想多了?


2
立刻浮现在脑海中的问题是“为什么”? - Matthew Scharley
在我的脑海中做某事。为什么? - Sherif
@MatthewScharley 我来这里是为了“自动化”。。 - A.D.
3个回答

10
以下将设置鼠标位置并执行点击操作:
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()'方法。


但是如果我想在屏幕上点击任何东西,有什么方法吗?还是我的想象力到此为止了? - Sherif
if作用域中的异常每次都会发生。我该怎么办? - Sherif
1
请记住,SendInput 的第二个参数应该是 ref,否则签名不匹配,会导致 PInvoke 异常! - Theodoros Chatzigiannakis
我猜这个只能在Windows系统上运行,对吧? - Andrew

7

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

使用Cursor.Position属性在c# .NET Framework 4.0中更加简单。

https://learn.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);
    }

1

定位鼠标的最简单方法:

对于左侧位置,使用左零;对于顶部位置,使用右零(您可以将其更改为任何数字)(要使用此代码,您需要使用using System.Drawingusing System.Windows.Forms命名空间)

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接