【发布时间】:2019-12-26 13:56:40
【问题描述】:
我创建了一个自定义按钮(关闭按钮),如下所示:
当我将鼠标移到按钮上时,它的颜色变为红色,如下所示:
当鼠标悬停在按钮上时,我想将按钮上的“X”重绘为白色,看起来像这样(我已经在油漆中修改了上面的图像以显示我希望它的外观):
我不知道该怎么做。
我的自定义按钮基本上继承自常规 Button 控件,并带有一些自定义设置。代码如下:
public class CloseButton : Button
{
public CloseButton()
{
this.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.FlatAppearance.BorderSize = 0;
this.FlatAppearance.MouseDownBackColor = System.Drawing.Color.IndianRed;
this.FlatAppearance.MouseOverBackColor = System.Drawing.Color.DarkRed;
this.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Size = new System.Drawing.Size(50, 30);
this.UseVisualStyleBackColor = true;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
GraphicsPath gPath;
Pen gPen;
gPen = new Pen(System.Drawing.SystemColors.ControlText);
gPath = new GraphicsPath();
gPath.AddLine(20, 10, 30, 20);
gPath.CloseFigure();
gPath.AddLine(20, 20, 30, 10);
gPath.CloseFigure();
e.Graphics.DrawPath(gPen, gPath);
}
}
我已尝试更改 OnPaint() 方法,以便笔颜色由控件的背景色确定,如下所示:
if ((this.BackColor.Equals(System.Drawing.Color.DarkRed) || this.BackColor.Equals(System.Drawing.Color.IndianRed))
{
gPen = new Pen(System.Drawing.SystemColors.ControlLightLight;
}
else
{
gPen = new Pen(System.Drawing.SystemColors.ControlText;
}
然后在我的 MouseEnter 和 Click 处理程序中,我使控件无效并刷新如下:
_BtnClose.Invalidate();
_BtnClose.Refresh();
这没有任何作用。我怎样才能实现我想要做的事情?如果我被卡住了,我总是可以创建另一个带有白色 X 的自定义按钮,并根据需要显示/隐藏此按钮,但如果可能的话,我想避免这样做
【问题讨论】:
-
MouseOverBackColor 在按钮渲染器中用于绘制按钮,它不会改变 BackColor。考虑一个简单的 bool 字段,在 OnMouseEnter() 中设置为 true,在 OnMouseLeave() 中设置为 false。