如何在C#中将鼠标光标位置设置为屏幕上的指定点?
我必须入侵接收鼠标和键盘坐标和按键的主板缓冲区吗?
还有其他方法可以进行点击操作,还是我想多了?
如何在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()'
方法。
SendInput
的第二个参数应该是 ref
,否则签名不匹配,会导致 PInvoke 异常! - Theodoros Chatzigiannakis在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);
}
定位鼠标的最简单方法:
对于左侧位置,使用左零;对于顶部位置,使用右零(您可以将其更改为任何数字)(要使用此代码,您需要使用using System.Drawing
和using System.Windows.Forms
命名空间)
Cursor.Position = new Point(0,0);