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

时间:2017-04-19 12:10:09

标签: c# winforms visual-studio-2017

在我的程序中我有一个分组框,我不喜欢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);
    }
}

工作“很好”,我给自己设置了一个黑色边框组合框而不是灰色,除非移动窗口时组框出现问题,picture

有没有修复此问题,还是必须使用visual studio组框来防止此问题?我正在使用C#winforms

1 个答案:

答案 0 :(得分:2)

PaintEventArgs.ClipRectangle的文档具有误导性 - 获取要绘制的矩形。。实际上,此属性表示窗口的无效矩形,它并不总是完整的矩形。它可以用来跳过那个矩形之外的元素的绘画,但不能作为绘画的基础。

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