自动在屏幕上点击鼠标
答
当你只是想一般的方式,我并没有真正做到尽善尽美,但这里的理念是:
有采取截屏的方法:
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)对此实现进行DRASTICALLY改进。
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;
}
然后,使用将成为:
对不起?我不明白一个字。 – JohnB
你需要进一步澄清你的意思。你是否要告诉它在哪里点击或是否需要以某种方式找到红色框?如果有两个红色的盒子会怎样?有多少像素可以定义一个“盒子”等等 – GazTheDestroyer
@GazTheDestroyer我并不是在寻找一个解决方案,只是一种实现方式,对于这种情况,屏幕上只会有一个红色框 –