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

Category: c# language

Question

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?

Replies

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


Hello,

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

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

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


Hi,

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

http://msdn.microsoft.com/en-us/library/system.drawing.graphics.copyfromscreen.aspx

http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.getpixel.aspx

Regards,

  Thorsten

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