如何在C#中将鼠标光标位置设置到屏幕上的指定点?
我必须知道接收鼠标和键盘坐标的主板缓冲区并按下???
是否有另一个点击或我想象???
答案 0 :(得分:7)
以下将设置鼠标位置并执行单击:
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()'
方法。
答案 1 :(得分:3)
获取并设置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);
}