在屏幕上自动点击鼠标

Jam*_*are 2 .net c# windows automation

我正在寻找一种创建程序的方法,该程序将在屏幕上找到某种颜色时执行鼠标单击.

例如,如果屏幕上有一个红色框,我希望程序点击它中心的红色框.

我怎样才能在C#中实现这一目标?

Sim*_*Var 6

因为你只想要一般的方式,我并没有真正完美,但这里的想法是:

有一个拍摄屏幕截图的方法:

public Bitmap ScreenShot()
{
    var screenShot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                Screen.PrimaryScreen.Bounds.Height,
                                PixelFormat.Format32bppArgb);

    using (var g = Graphics.FromImage(screenShot))
    {
        g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);
    }

    return screenShot;
}
Run Code Online (Sandbox Code Playgroud)

以及在位图中查找某种颜色的方法:请注意,使用不安全的代码和LockBits(此处此处阅读)可以彻底改进此实现.

public Point? GetFirstPixel(Bitmap bitmap, Color color)
{
    for (var y = 0; y < bitmap.Height; y++)
    {
        for (var x = 0; x < bitmap.Width; x++)
        {
            if (bitmap.GetPixel(x, y).Equals(color))
            {
                return new Point(x, y);
            }
        }
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

您需要的另一种方法是单击某个点:

[DllImport("user32.dll",
           CharSet=CharSet.Auto,
           CallingConvention=CallingConvention.StdCall)]
private static extern void mouse_event(long dwFlags,
                                      long dx,
                                      long dy,
                                      long cButtons,
                                      long dwExtraInfo);

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

public void Click(Point pt)
{
    Cursor.Position = pt;
    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, pt.X, pt.Y, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)

最后,一个包装起来:

public bool ClickOnFirstPixel(Color color)
{
    var pt = GetFirstPixel(ScreenShot(), color);

    if (pt.HasValue)
    {
        Click(pt.Value);
    }

    // return whether found pixel and clicked it
    return pt.HasValue;
}
Run Code Online (Sandbox Code Playgroud)

然后,用法将是:

if (ClickOnFirstPixel(Color.Red))
{
    Console.WriteLine("Found a red pixel and clicked it!");
}
else
{
    Console.WriteLine("Didn't find a red pixel, didn't click.");
}
Run Code Online (Sandbox Code Playgroud)