【问题标题】:How can I simulate a mouse click at a certain position on the screen?如何在屏幕上的某个位置模拟鼠标单击?
【发布时间】:2012-01-06 13:04:41
【问题描述】:

我想做的是操纵鼠标。出于我自己的目的,这将是一个简单的宏。所以它会把我的鼠标移动到屏幕上的某个位置,然后像我按一定的间隔点击一样点击。

【问题讨论】:

  • this 是您需要的吗?此外,正如 cmets 中有人建议的那样,您可能想要使用 UIAutomation。

标签: c# wpf c#-4.0 click mouse


【解决方案1】:

这是一个使用非托管函数来模拟鼠标点击的代码:

//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 线程上执行此代码,因为它会导致它挂起

【讨论】:

  • 这比我在这里看到的其他解决方案要简单得多。谢谢
  • 这段代码可以很好地将指针带到屏幕上所需的坐标,但由于某种原因,点击对我不起作用。知道为什么吗?
  • 这里你可以得到其他鼠标按钮的代码:msdn.microsoft.com/en-us/library/windows/desktop/…
【解决方案2】:

您可以按 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

【讨论】:

  • 问题在于 WPF,而不是 Forms。
  • 不起作用:windows.Forms.Cursor.Position = New System.Drawing.Point(Button1.Location.X + Me.Location.X + 50, Button1.Location.Y + Me.Location .Y + 30) 。我也试过这个在没有提到的表格上不会在 wpf 工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
相关资源
最近更新 更多