Get pixel color in example

I searched for posts on this site and I came across this: How to get pixel color in X, Y using C #?

Will this method still be effective in order to get the color of the pixel only inside the form?

If not, what is the way to substantially “display” a form in a 2D array of color values?

For example, I have a Tron game, and I want to check if the next location of the light bike contains another light tank.

Thanks Ian

+3
source share
3 answers
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;
    }
}

Using this, you can:

public static class ControlExts
{
    public static Color GetPixelColor(this Control c, int x, int y)
    {
        var screenCoords = c.PointToScreen(new Point(x, y));
        return Win32.GetPixelColor(screenCoords.X, screenCoords.Y);
    }
}

So in your case you can do:

var desiredColor = myForm.GetPixelColor(10,10);
+3
source

You can use the GetPixel method to get the color.

eg.

// Bitmap . Bitmap myBitmap = ( "Grapes.jpg" );

// myBitmap. pixelColor = myBitmap.GetPixel(50, 50);

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

, , , , , .

: , , - ! , , ...

0

All Articles