How to get the colour of a pixel at X,Y using c#?

How do I get the color of a pixel at X,Y using c#?

As for the result, I can convert the results to the color format I need. I am sure there is an API call for this.

For any given X,Y on the monitor, I want to get the color of that pixel.


Solution 1:

To get a pixel color from the Screen here's code 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;
      }
   }

Solution 2:

There's Bitmap.GetPixel for an image... is that what you're after? If not, could you say which x, y value you mean? On a control?

Note that if you do mean for an image, and you want to get lots of pixels, and you don't mind working with unsafe code, then Bitmap.LockBits will be a lot faster than lots of calls to GetPixel.

Solution 3:

Aside from the P/Invoke solution, you can use Graphics.CopyFromScreen to get the image data from the screen into a Graphics object. If you aren't worried about portability, however, I would recommend the P/Invoke solution.

Solution 4:

For ref in WPF: (usage of PointToScreen)

    System.Windows.Point position = Mouse.GetPosition(lightningChartUltimate1);

    if (lightningChartUltimate1.ViewXY.IsMouseOverGraphArea((int)position.X, (int)position.Y))
    {
        System.Windows.Point positionScreen = lightningChartUltimate1.PointToScreen(position);
        Color color = WindowHelper.GetPixelColor((int)positionScreen.X, (int)positionScreen.Y);
        Debug.Print(color.ToString());


      ...

      ...


public class WindowHelper
{
    // ******************************************************************
    [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.Windows.Media.Color GetPixelColor(int x, int y)
    {
        IntPtr hdc = GetDC(IntPtr.Zero);
        uint pixel = GetPixel(hdc, x, y);
        ReleaseDC(IntPtr.Zero, hdc);
        Color color = Color.FromRgb(
            (byte)(pixel & 0x000000FF),
            (byte)((pixel & 0x0000FF00) >> 8),
            (byte)((pixel & 0x00FF0000) >> 16));
        return color;
    }