Winforms有彩色边框的groupbox

时间:2014-02-17 08:50:49

标签: vb.net winforms groupbox

我使用以下代码创建了带彩色边框的组合框:

Public Class BorderGroupBox
    Inherits GroupBox

    Private _borderColor As Color
    Private _borderWidth As Integer
    Private _borderStyle As ButtonBorderStyle

    ...

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        Dim tSize As Size = TextRenderer.MeasureText(Me.Text, Me.Font)
        Dim borderRect As Rectangle = e.ClipRectangle
        borderRect.Y = CInt((borderRect.Y + (tSize.Height / 2)))
        borderRect.Height = CInt((borderRect.Height - (tSize.Height / 2)))
        ControlPaint.DrawBorder(e.Graphics, borderRect, _borderColor, _borderWidth, _borderStyle, BorderColor, _borderWidth, _borderStyle, BorderColor, _borderWidth, _borderStyle, BorderColor, _borderWidth, _borderStyle)
        Dim textRect As Rectangle = e.ClipRectangle
        textRect.X = (textRect.X + 6)
        textRect.Width = tSize.Width + 6
        textRect.Height = tSize.Height
        e.Graphics.FillRectangle(New SolidBrush(Me.BackColor), textRect)
        e.Graphics.DrawString(Me.Text, Me.Font, New SolidBrush(Me.ForeColor), textRect)
    End Sub
End Class

问题是,它被放置在一个可滚动的容器内,如果滚动它,边框不会正确重绘:

Redraw

3 个答案:

答案 0 :(得分:6)

你可能会比这更糟糕的是:

enter image description here

由于使用e.ClipRectangle的代码,这会出错。请注意,它在您的代码段中显示两次。该变量为您提供边框矩形。它告诉您需要重新绘制多少客户区域。这是一个优化机会,您可以通过省略不需要刷新的客户区部分来减少绘制。

通常与显示矩形的大小相同,这就是它看起来效果很好的原因。但是当你把它放在一个可滚动的容器中时,Windows不会通过blitting客户区的可以移动的部分来优化滚动。然后为滚动显示的部件生成一个颜料。用一个小的e.ClipRectangle。您可以在屏幕截图中看到小矩形。

将e.ClipRectangle替换为Me.DisplayRectangle。

答案 1 :(得分:1)

此类允许为所有框设置边框,或者通过向组框的属性选项卡添加边框颜色控件来单独设置边框。

Public Class GroupBoxA
    Inherits GroupBox

    Private _borderColor As Color

    Public Sub New()
        MyBase.New()
        Me._borderColor = Color.OrangeRed
    End Sub

    Public Property BorderColor() As Color
        Get
            Return Me._borderColor
        End Get
        Set(ByVal value As Color)
            Me._borderColor = value
        End Set
    End Property

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        Dim tSize As Size = TextRenderer.MeasureText(Me.Text, Me.Font)
        Dim borderRect As Rectangle = Me.DisplayRectangle

        borderRect.Y = (borderRect.Y + (tSize.Height / 2))
        borderRect.Height = (borderRect.Height - (tSize.Height / 2))

        ControlPaint.DrawBorder(e.Graphics, borderRect, Me._borderColor,
                                ButtonBorderStyle.Solid)

        Dim textRect As Rectangle = Me.DisplayRectangle
        textRect.X = (textRect.X + 6)
        textRect.Width = tSize.Width
        textRect.Height = tSize.Height

        e.Graphics.FillRectangle(New SolidBrush(Me.BackColor), textRect)
        e.Graphics.DrawString(Me.Text, Me.Font, New SolidBrush(Me.ForeColor), textRect)
    End Sub
End Class

答案 2 :(得分:-1)

你必须使用Me.ClientRectangle而不是Me.DisplayRectangle来表示boder和text。如果您使用旧方式,则闪烁问题无法解决,并且组框的文本将不会显示。

相关问题