如何在 C# 中将鼠标光标位置设置到屏幕上的指定点?
我是否必须破解接收鼠标和键盘坐标并按下的主板缓冲区?
还有其他人可以点击还是我想象???
以下将设置鼠标位置并执行单击:
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()'
方法。
在 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);
}
最简单的鼠标定位方法:
左侧位置为零,顶部位置为零(您可以将其更改为您想要的任何数字)(要使用此代码,您需要使用using System.Drawing
和using System.Windows.Forms
命名空间)
Cursor.Position = new Point(0,0);