我正在寻找一种创建程序的方法,该程序将在屏幕上找到某种颜色的地方单击鼠标。
例如,如果屏幕上有一个红色框,我希望程序单击它中间的红色框。
如何在C#中完成此操作?
最佳答案
正如您只想使用一般方法一样,我并没有真正使其完美,但是这里是这样的想法:
有一种截屏方法:
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;
}
还有一种在位图中查找某种颜色的方法:请注意,可以使用不安全的代码和LockBits(请阅读here和here)来彻底改进此实现。
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;
}
您需要的另一种方法是单击某个点:[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);
}
最后,一个总结一下: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;
}
然后,用法为: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.");
}
关于c# - 自动在屏幕上单击鼠标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10870303/