0

I have draw a rectangle as:

Rectangle rectangle=new Rectangle(10,10,40,40);
g.FillRectangle(new SolidBrush(Color.Red),rectangle);

can somebody give me any idea that is it possible to get the background color of a rectangle when clicked:

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
            if (rectangle.Contains(e.Location))
            {
                //get the color here that it should be Red
                Console.WriteLine("COLOR IS: " ????);
            }
}

Thanks in advance

Tim
  • 38,263
  • 17
  • 115
  • 131
Java Nerd
  • 868
  • 3
  • 15
  • 51
  • If you draw a rectangle on your form, then you would need to do that in a paint event to redraw the rectangle whenever the form is redrawn. Thus, you need to keep both the rectangle and the color, and you should be able to just get that color when you have determined that the click is inside the rectangle. If you don't draw the rectangle in a paint event, then you haven't drawn it on the form, you have drawn it on the screen in the place where the form also happens to be drawn. – Guffa May 26 '14 at 13:52

1 Answers1

1

Take a look at this answer.

The basic idea is to get the color of the pixel where the click event is fired (e.Location) and for that you can use gdi32.dll's GetPixel method.

A slightly modified version of the code found at the link:

class PixelColor
{
    [DllImport("gdi32")]
    public static extern uint GetPixel(IntPtr hDC, int XPos, int YPos);

    [DllImport("User32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr GetWindowDC(IntPtr hWnd);

    /// <summary> 
    /// Gets the System.Drawing.Color from under the given position. 
    /// </summary> 
    /// <returns>The color value.</returns> 
    public static Color Get(int x, int y)
    {
        IntPtr dc = GetWindowDC(IntPtr.Zero);

        long color = GetPixel(dc, x, y);
        Color cc = Color.FromArgb((int)color);
        return Color.FromArgb(cc.B, cc.G, cc.R);
    }
}

Please note that you may have to transform you X and Y coordinates to screen coordinates before calling the function.

But in your case the real answer is: Red. :)

Community
  • 1
  • 1
qqbenq
  • 8,737
  • 3
  • 33
  • 41