0

特定の色を持つ最初のピクセルをクリックするプログラムを作成しようとしています。残念ながら、画面上に実際に色があることをプログラムが検出できないことがあるようです。画面のスクリーンショットを撮り、GetPixel() メソッドを使用してすべてのピクセルの色を見つけます。

これが私が使用する私の方法です:

private static Point FindFirstColor(Color color)
{
    int searchValue = color.ToArgb();
    Point location = Point.Empty;

    using (Bitmap bmp = GetScreenShot())
    {
        for (int x = 0; x < bmp.Width; x++)
        {
            for (int y = 0; y < bmp.Height; y++)
            {
                if (searchValue.Equals(bmp.GetPixel(x, y).ToArgb()))
                {
                    location = new Point(x, y);
                }
            }
        }
    }
    return location;
}

画面のスクリーンショットを撮るために、次を使用します。

private static Bitmap GetScreenShot()
    {
        Bitmap result = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
        {
            using (Graphics gfx = Graphics.FromImage(result))
            {
                gfx.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
            }
        }
        return result;
    }

画面上にあることがわかっている色を使用しても、Point.Empty が返されます。これの理由は何ですか?

4

1 に答える 1

1

Just copied your method and used as color the find Color.Black and it worked without any problems.

The only thing that's currently maybe not correctly in your code is that you don't immediately return after finding the first matching point. Instead you simply continue to iterate over all points thus leading to the fact that you'll going to return the last occurrence of a matching color.

To avoid this you can change your code into:

private static Point FindFirstColor(Color color)
{
    int searchValue = color.ToArgb();

    using (Bitmap bmp = GetScreenShot())
    {
        for (int x = 0; x < bmp.Width; x++)
        {
            for (int y = 0; y < bmp.Height; y++)
            {
                if (searchValue.Equals(bmp.GetPixel(x, y).ToArgb()))
                {
                    return new Point(x, y);
                }
            }
        }
    }

    return Point.Empty;
}
于 2012-12-21T07:44:49.033 に答える