我有UserControl
,其上有button
。在UserControl
OnPaint
事件中,我绘制一个圆角边框(如果半径为零,则绘制一个简单的矩形),然后填充整个控件。在这些操作之后,我Button
(btnClose
)消失了。
如何让我的button
再次可见?
protected override void OnPaint(PaintEventArgs pe)
{
using (System.Drawing.Pen p = new Pen(new SolidBrush(this.BorderColor)))
{
if (borderRadius > 0)
{
DrawRoundRect(pe.Graphics, p, 0, 0, this.Width - 1, this.Height - 1, borderRadius, this.FillColor);
}
else
{
this.BackColor = this.FillColor;
pe.Graphics.DrawRectangle(p, 0, 0, this.Width - 1, this.Height - 1);
}
btnClose.Location = new Point(this.Width - btnClose.Width - BTN_MARGIN_DELTA, BTN_MARGIN_DELTA);
}
base.OnPaint(pe);
}
以防万一,DrawRoundRect函数:
void DrawRoundRect(Graphics g, Pen p, float X, float Y, float width, float height, float radius, Color _fillColor)
{
using (GraphicsPath gp = new GraphicsPath())
{
gp.AddLine(X + radius, Y, X + width - (radius * 2), Y);
gp.AddArc(X + width - (radius * 2), Y, radius * 2, radius * 2, 270, 90);
gp.AddLine(X + width, Y + radius, X + width, Y + height - (radius * 2));
gp.AddArc(X + width - (radius * 2), Y + height - (radius * 2), radius * 2, radius * 2, 0, 90);
gp.AddLine(X + width - (radius * 2), Y + height, X + radius, Y + height);
gp.AddArc(X, Y + height - (radius * 2), radius * 2, radius * 2, 90, 90);
gp.AddLine(X, Y + height - (radius * 2), X, Y + radius);
gp.AddArc(X, Y, radius * 2, radius * 2, 180, 90);
gp.CloseFigure();
using (SolidBrush brush = new SolidBrush(_fillColor))
{
g.FillPath(brush, gp);
g.DrawPath(p, gp);
}
}
}
答案 0 :(得分:1)
尝试将位置代码移动到resize方法:
protected override void OnResize(EventArgs e) {
btnClose.Location = new Point(this.Width - btnClose.Width - BTN_MARGIN_DELTA, BTN_MARGIN_DELTA);
}
在paint事件中移动控件可能会导致对paint事件的递归调用。只在油漆事件中“画画”。
答案 1 :(得分:0)
我设置FillColor = Color.Gray
,BorderColor = Color.Black
,borderRadius = 5
,BTN_MARGIN_DELTA = 2
,它似乎没有任何问题。这是一个截图:
我认为问题不在于这些代码行。
答案 2 :(得分:0)
好吧,我的错误。这是一个从UserControl删除所有控件的函数。所以我在删除时过滤了控件。
void ClearControls()
{
for (int i = 0; i < Items.Count; i++)
{
foreach (Control cc in Controls)
{
if (cc.Name.Contains(LINK_LABEL_FAMILY) || (cc.Name.Contains(LABEL_FAMILY)))
{
Controls.RemoveByKey(cc.Name);
}
}
}
}