0

我有一个上面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);
        }
    }
}
4

3 回答 3

1

尝试将位置代码移动到 resize 方法:

protected override void OnResize(EventArgs e) {
  btnClose.Location = new Point(this.Width - btnClose.Width - BTN_MARGIN_DELTA, BTN_MARGIN_DELTA);
}

在绘制事件中移动控件可能会导致对绘制事件的递归调用。仅在绘画事件中“绘画”。

于 2013-01-18T18:03:36.570 回答
0

我设置了FillColor = Color.Gray, BorderColor = Color.Black, borderRadius = 5BTN_MARGIN_DELTA = 2它似乎没有任何问题。这是一个屏幕截图:

在此处输入图像描述

我认为问题不在于这些代码行。

于 2013-01-18T18:05:29.257 回答
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);
            }
        }
    }
}
于 2013-01-18T18:29:21.280 回答