It’s hard to believe the comprehensive .NET framework would omit such obvious functions as GetPixel and SetPixel from its Drawing library. Fortunately, we can access the GDI functions using Interop, as shown below. Notice the conversion required between the COLORREF integer used by the GDI methods and the Color structure used by our static .NET methods.

using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

[DllImport( "user32.dll" )]
static extern IntPtr GetDC( IntPtr hWnd );
[DllImport( "user32.dll" )]
static extern int ReleaseDC( IntPtr hWnd, IntPtr hDC );
[DllImport( "gdi32.dll" )]
static extern int GetPixel( IntPtr hDC, int x, int y );
[DllImport( "gdi32.dll" )]
static extern int SetPixel( IntPtr hDC, int x, int y, int color );

static public Color GetPixel( Control control, int x, int y )
{
    Color color = Color.Empty;
    if (control != null)
    {
        IntPtr hDC = GetDC( control.Handle );
        int colorRef = GetPixel( hDC, x, y );
        color = Color.FromArgb(
            (int)(colorRef & 0x000000FF),
            (int)(colorRef & 0x0000FF00) >> 8,
            (int)(colorRef & 0x00FF0000) >> 16 );
        ReleaseDC( control.Handle, hDC );
    }
    return color;
}
static public void SetPixel( Control control, int x, int y, Color color )
{
    if (control != null)
    {
        IntPtr hDC = GetDC( control.Handle );
        int argb = color.ToArgb();
        int colorRef =
            (int)((argb & 0x00FF0000) >> 16) |
            (int)(argb & 0x0000FF00) |
            (int)((argb & 0x000000FF) << 16);
        SetPixel( hDC, x, y, colorRef );
        ReleaseDC( control.Handle, hDC );
    }
}

NOTE: These functions will not return the correct color if the specified control uses an alpha channel. In that case, you will have to create a Bitmap from the control, then use the Bitmap’s GetPixel method.

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot