How doI test the color of a certain pixel or point?

Category: c# language


I just want to ask a question on Tue, 18 Sep 2012 00:27:08

I want to test the color of a certain point on the screen outside of the form window. How can I do this?


Hillin on Tue, 18 Sep 2012 02:52:50


You can use P/Invoke to call the GetPixel API. Here is a wrapper class do that for you, from

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

  sealed class Win32
      static extern IntPtr GetDC(IntPtr hwnd);

      static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

      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;

Thorsten Gudera on Tue, 18 Sep 2012 11:52:25


you could use Graphics.CopyFromScreen() to get a Bitmap of the screen and use GetPixel to get the color at a given coordinate.



JohnWein on Tue, 18 Sep 2012 15:51:07

If you prefer .NET code rather than p/invoking the Windows API:

	public Color GetScreenPointColor(Point Pt)
		Color tempGetScreenPointColor = new Color();
		using (Bitmap Bmp = new Bitmap(1, 1))
			using (Graphics G = Graphics.FromImage(Bmp))
				G.CopyFromScreen(Pt, Point.Empty, Bmp.Size);
				tempGetScreenPointColor = Bmp.GetPixel(0, 0);
		return tempGetScreenPointColor;