get pixel color in instance

.net, c#, graphics, pixel

Solution

using System;
using System.Drawing;
using System.Runtime.InteropServices;

sealed class Win32
{
    [DllImport("user32.dll")]
    static extern IntPtr GetDC(IntPtr hwnd);

    [DllImport("user32.dll")]
    static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

    [DllImport("gdi32.dll")]
    static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

    static public System.Drawing.Color GetPixelColor(int x, int y)
    {
       IntPtr hdc = GetDC(IntPtr.Zero);
       uint pixel = GetPixel(hdc, x, y);
       ReleaseDC(IntPtr.Zero, hdc);
       Color color = Color.FromArgb((int)(pixel & 0x000000FF),
                    (int)(pixel & 0x0000FF00) >> 8,
                    (int)(pixel & 0x00FF0000) >> 16);
       return color;
    }
}

Using this, you can then do:

public static class ControlExts
{
    public static Color GetPixelColor(this Control c, int x, int y)
    {
        var screenCoords = c.PointToScreen(new Point(x, y));
        return Win32.GetPixelColor(screenCoords.X, screenCoords.Y);
    }
}

So, in your case you can do:

var desiredColor = myForm.GetPixelColor(10,10);

Problem

I was searching through the posts on this site and i came across this: How do I get the colour of a pixel at X,Y using c#? would this method still be effective for trying to get the colour of a pixel just inside a form? If not, what would be a way to essentially "map" the form in an 2D array of color values? For example, I have a Tron game, and I want to check to see if the next location of the lightbike already contains another lightbike. Thanks, Ian

Original source

Related problems