[英]Automating mouse clicks on screen
我正在尋找一種創建程序的方法,該程序將執行鼠標單擊,在屏幕上找到某種顏色。
例如,如果屏幕上有一個紅框,我希望程序點擊它中心的紅框。
我怎么能在 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(閱讀此處和此處)大幅改進此實現。
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.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.