如何在屏幕上模拟鼠标单击特定位置?

59

我想做的是操纵鼠标。这将是一个为了我自己目的而设计的简单宏。因此,它将移动我的鼠标到屏幕上的特定位置,并以特定间隔点击,就像我自己在点击一样。


1
这个链接是否是你需要的?另外,正如评论中有人建议的那样,你可能想要使用UIAutomation。 - Nasreddine
2个回答

80

以下是使用不受管理的函数模拟鼠标点击的代码:

//This is a replacement for Cursor.Position in WinForms
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;

//This simulates a left mouse click
public static void LeftMouseClick(int xpos, int ypos)
{
    SetCursorPos(xpos, ypos);
    mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
    mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
}

为了让鼠标按下一定时间,您可以Sleep()执行此函数的线程,例如:

mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
System.Threading.Thread.Sleep(1000);
mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);

以上代码将使鼠标保持按下状态1秒钟,除非用户按下并释放鼠标按钮。此外,请确保不要在主UI线程上执行此代码,否则会导致其挂起


1
这比我在这里看到的其他解决方案要简单得多。谢谢。 - Yablargo
2
这段代码可以将指针移动到屏幕上所需的坐标,但是出于某种原因,对我来说点击操作无效。有什么想法吗? - john
在这里,您可以获取其他鼠标按钮的代码:https://msdn.microsoft.com/zh-cn/library/windows/desktop/ms646260(v=vs.85).aspx - Li3ro

9
您可以通过XY位置进行移动。以下是示例:
windows.Forms.Cursor.Position = New System.Drawing.Point(Button1.Location.X + Me.Location.X + 50, Button1.Location.Y + Me.Location.Y + 30)

要执行点击操作,您可以使用以下代码:

using System.Runtime.InteropServices;

private const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002;
private const UInt32 MOUSEEVENTF_LEFTUP = 0x0004;
[DllImport("user32.dll")]
    private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData,             uint dwExtraInf);
private void btnSet_Click(object sender, EventArgs e)
    {
        int x = Convert.ToInt16(txtX.Text);//set x position 
        int y = Convert.ToInt16(txtY.Text);//set y position 
        Cursor.Position = new Point(x, y);
        mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);//make left button down
        mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);//make left button up
    }

感谢JOHNYKUTTY提供的帮助。


2
问题是关于WPF,而不是Forms。 - Vlad
1
无法工作:windows.Forms.Cursor.Position = New System.Drawing.Point(Button1.Location.X + Me.Location.X + 50, Button1.Location.Y + Me.Location.Y + 30)。我在窗体尝试了这个方法,但没有在WPF中测试过。 - Furkan Gözükara

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