UI 编写自己的组框时出现故障

UI glitch when writing own group box

在我的程序中我有一个分组框,我不喜欢 visual studio 中提供的 groupbx 没有边框颜色 属性 所以我使用这段代码创建了我自己的分组框。

public class MyGroupBox : GroupBox
{
    private Color _borderColor = Color.Black;

    public Color BorderColor
    {
        get { return this._borderColor; }
        set { this._borderColor = value; }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        //get the text size in groupbox
        Size tSize = TextRenderer.MeasureText(this.Text, this.Font);

        Rectangle borderRect = e.ClipRectangle;
        borderRect.Y = (borderRect.Y + (tSize.Height / 2));
        borderRect.Height = (borderRect.Height - (tSize.Height / 2));
        ControlPaint.DrawBorder(e.Graphics, borderRect, this._borderColor, ButtonBorderStyle.Solid);

        Rectangle textRect = e.ClipRectangle;
        textRect.X = (textRect.X + 6);
        textRect.Width = tSize.Width;
        textRect.Height = tSize.Height;
        e.Graphics.FillRectangle(new SolidBrush(this.BackColor), textRect);
        e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), textRect);
    }
}

有效 "fine",我给自己设置了一个黑色边框组框而不是灰色,除非移动 window 组框会像这样出现故障,

是否有解决此问题的方法,或者我是否必须使用 visual studio 组框来防止此问题?我正在使用 C# winforms

PaintEventArgs.ClipRectangle 的文档具有误导性 - 获取要绘制的矩形。。实际上这个 属性 表示 window 的 invalidated 矩形,它并不总是完整的矩形。它可用于跳过矩形外元素的绘制,但不能作为绘制的基础。

但是所有绘制的基本矩形应该是被绘制控件的 ClientRectangle 属性。所以只需将 e.ClipRectangle 替换为 this.ClientRectangle.