1

I need to detect the color of a pixel on my monitor. How do I retrieve it on coordinate (x,y) in C#?

Kasper Hansen
  • 6,307
  • 21
  • 70
  • 106

4 Answers4

5

Use Graphics.CopyFromScreen to copy a 1x1 bitmap, Bitmap.GetPixel() to get its color.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
2

First Import these Dlls

    [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);

Then write this method GetPixelColor(x,y);

      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;
      }

Call the method Color clr= GetPixelcolor(50,50);

PawanS
  • 7,033
  • 14
  • 43
  • 71
1

First, capture the screen.

Rectangle screenRegion = Screen.AllScreens[0].Bounds;
Bitmap screen = new Bitmap(screenRegion.Width, screenRegion.Height, PixelFormat.Format32bppArgb);

Graphics screenGraphics = Graphics.FromImage(screenBitmap);
screenGraphics.CopyFromScreen(screenRegion.Left, screenRegion.Top, 0, 0, screenRegion.Size);

Then, get the pixel from the bitmap.

Community
  • 1
  • 1
Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
  • Note that it works only with the primary monitor. If you need to capture a pixel from other monitors, you have to change the zero index at the first line of the code. – Arseni Mourzenko Nov 17 '10 at 12:03
0

You can use winapi GetPixel(...)

Servy
  • 202,030
  • 26
  • 332
  • 449
pyCoder
  • 503
  • 3
  • 9