C# 获取矩形的背景色
我画了一个矩形,如下所示:C# 获取矩形的背景色,c#,drawrectangle,C#,Drawrectangle,我画了一个矩形,如下所示: Rectangle rectangle=new Rectangle(10,10,40,40); g.FillRectangle(new SolidBrush(Color.Red),rectangle); 有没有人能告诉我,单击时是否可以获得矩形的背景色: private void Form1_MouseClick(object sender, MouseEventArgs e) { if (rectangle.Contains(e.Locat
Rectangle rectangle=new Rectangle(10,10,40,40);
g.FillRectangle(new SolidBrush(Color.Red),rectangle);
有没有人能告诉我,单击时是否可以获得矩形的背景色:
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: " ????);
}
}
提前感谢看看这个
基本思想是获取触发单击事件的像素的颜色(e.Location
),为此,可以使用gdi32.dll的GetPixel
方法
在链接中找到的代码的稍微修改版本:
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);
}
}
类像素颜色
{
[DllImport(“gdi32”)]
公共静态外部单元GetPixel(IntPtr hDC、intxpos、intypos);
[DllImport(“User32.dll”,CharSet=CharSet.Auto)]
公共静态外部IntPtr GetWindowDC(IntPtr hWnd);
///
///从给定位置下获取System.Drawing.Color。
///
///颜色值。
公共静态颜色获取(int x,int y)
{
IntPtr dc=GetWindowDC(IntPtr.Zero);
长颜色=GetPixel(dc,x,y);
Color cc=Color.FromArgb((int)Color);
从argb返回颜色(cc.B,cc.G,cc.R);
}
}
请注意,在调用函数之前,可能需要将X和Y坐标转换为屏幕坐标
但对你来说,真正的答案是:红色 如果在表单上绘制矩形,则需要在绘制事件中执行此操作,以便在重新绘制表单时重新绘制矩形。因此,您需要同时保留矩形和颜色,并且当您确定单击位于矩形内部时,应该能够获得该颜色。如果您没有在绘制事件中绘制矩形,那么您没有在窗体上绘制矩形,您已经在屏幕上恰好绘制窗体的位置绘制了矩形。