我想从屏幕上找到一个特定的像素坐标。这是我的代码(我是 super 新手,我今天才开始使用 C#:
static string GetPixel(int X, int Y)
{
Point position = new Point(X, Y);
var bitmap = new Bitmap(1, 1);
var graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(position, new Point(0, 0), new Size(1, 1));
var _Pixel = bitmap.GetPixel(0, 0);
return "0x" + _Pixel.ToArgb().ToString("x").ToUpper().Remove(0, 2);
//it returns a pixel color in a form of "0xFFFFFF" hex code
//I had NO idea how to convert it to hex code so I did that :P
}
static void Main()
{
// for x = 1 to screen width...
for (int x = 1; x <= Screen.PrimaryScreen.Bounds.Bottom; x++)
{
// for x = 1 and y = 1 to screen height...
for (int y = 1; y <= Screen.PrimaryScreen.Bounds.Height; y++)
{
string pixel = GetPixel(x, y);
if (pixel == "0x007ACC") //blue color
{
MessageBox.Show("Found 0x007ACC at: (" + x + "," + y + ")");
break; //exit loop
}
}
}
}
编辑: 这是我运行此脚本时出现的错误:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index and length must refer to a location within the string
我有 AutoIt 经验,这是我第一天使用 C# ^^ 问候
最佳答案
欢迎来到 SO。
大多数坐标和其他东西都是从 0 开始的,就像在数组中一样。
也就是说,最好对循环使用边界的 X/Y/宽度和高度属性:
var bounds = Screen.PrimaryScreen.Bounds;
for (int x = bounds.X; x < bounds.Width; x++) {
for(int y = bounds.Y; y < bounds.Height; y++) {
..
将 ARGB 值转换为十六进制的正确方法是使用 string.Format()方法:
string hex = string.Format("0x{0:8x}", argb);
编辑: 显然 Graphics.CopyFromScreen
泄漏句柄就像没有明天一样,这会导致在没有更多句柄可用时抛出奇怪的异常 ( source )
您的场景的快速解决方法可能是捕获整个屏幕一次,然后在位图中搜索,即 Graphics.CopyFromScreen(new Position(0, 0), new Position(0, 0), new Size (bounds.Width, bounds.Height));
不幸的是,这在 .Net 4.0 中没有得到修复(不知道 4.5),所以唯一正确的解决方案似乎是 P/Invoke native GDI 函数,如所述 here .
关于c# - 在屏幕上搜索 Pixel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13531939/