pooya mahmoodi pooya mahmoodi - 2 months ago 16
Vb.net Question

create a custom label with BorderColor property

I try to create a label with BorderColor property.but it not work . I create an instant object of this label in my form application and try to change the BorderColor , but nothing is happen.
this is my code :

Public Class MyLabel
Inherits Label

Private _BorderColor As Color
Dim e As New PaintEventArgs(Me.CreateGraphics, Me.DisplayRectangle)

Public Property BorderColor As Color
Get
Return _BorderColor
End Get
Set(value As Color)
_BorderColor = value
CreateBorder(value)
End Set
End Property

Private Sub CreateBorder(ByVal value As Color)
Dim g As Graphics = Me.CreateGraphics
Dim p As Pen = New Pen(value, 2)
g.DrawRectangle(p, Me.DisplayRectangle)
End Sub

Private Sub MyLabel_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
CreateBorder(_BorderColor)
End Sub


End Class

Answer

No, no and double no. You DO NOT call CreateGraphics. A Graphics object is provided to you by the Paint event and you use that. Also, you don't handle the Paint event in a custom control but rather override the OnPaint method. Furthermore, if you have a method that does the drawing, e.g. CreateBorder, then you DO NOT call it from anywhere but the OnPaint method. If you want to ensure that the border is repainted on the next event then you call Invalidate. E.g.

Public Class BorderedLabel
    Inherits Label

    Private _borderColor As Color

    Property BorderColor As Color
        Get
            Return _borderColor
        End Get
        Set
            _borderColor = Value
            Invalidate()
        End Set
    End Property

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)

        Using p As New Pen(BorderColor, 2)
            e.Graphics.DrawRectangle(p, DisplayRectangle)
        End Using
    End Sub

End Class