c# - 在屏幕上搜索 Pixel

标签 c# search find screen pixel

我想从屏幕上找到一个特定的像素坐标。这是我的代码(我是 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/

相关文章:

c# - ActionFilterAttribute 是否为每个 Action 实例化?

java - 如果已经找到数组,则无法删除该数组(数组搜索排序)

sql-server - 在 SQL Server 中存储 DateTime 以在大型表中提供最大搜索速度的最佳方法是什么?

php - 使用 "LIKE"匹配mysql查询中的多个单词

loops - Solidworks 宏在每个工程图上查找和替换

Linux命令递归地用目录名称中的-(破折号)替换空格?

Java elasticsearch,按单词的一部分查找

c# - 如何允许 SignalR 使用 EF6 将更新从数据库推送到浏览器

c# - Linq 中的 DocumentDb 空间距离返回奇怪的结果

c# - 如何在 ASP .NET MVC 5.1 Web 应用程序的 Entity Framework 中使用散列 ID 以避免指向数据库中记录的可预测链接