Painting a label's background ?

ALX

Well-known member
Joined
Nov 16, 2005
Messages
253
Location
Columbia, SC
Programming Experience
10+
I would like to paint the background of a label with a gradient brush and have the text in the label handled by the system rather than painting the text myself. I've been looking at overriding the 'OnPaintBackground' method but I can only get it to work with the form's background rather that the label's background. How does one override 'OnPaintBackground' with individual controls (labels) ???
 
This is from the documentation for the OnPaintBackground method:
Notes to Inheritors Inheriting classes should override this method to handle the erase background request from windows. When overriding OnPaintBackground in a derived class it is not necessary to call the base class's OnPaintBackground. However, if you do not want the default Windows behavior, you must set the event's Handled property to true.
Did you honour that last condition?
 
OK! Apparently I can't see the forest for the trees. Any reference material I look at has this method that I need to override:
' Control.OnPaintBackground Method - *Paints the background of the control.

Protected Overridable Sub OnPaintBackground( ByVal pevent As PaintEventArgs)

I have a form with one label named "Label1":
I want to paint the background of Label1:
By looking at the very brief discription that MS gives for the above sub, I would need to include in my code the following:

VB.NET:
     Protected Overrides Sub Label1.OnPaintBackground(ByVal e As System.Windows.Forms.PaintEventArgs)
        '...
     End Sub

This immediately generates the error:
"End of statement expected"
Obviously, I'm just not getting it !
 
Where did you put that code? In a form? You can't override a member of an object. You override a member of a class and you do it inside that class. If you want to override a member of the Label class then you have to declare your own class that inherits the Label class, e.g.
VB.NET:
Public Class LabelEx
    Inherits System.Windows.Forms.Label

    Protected Overrides Sub OnPaintBackground(ByVal e As System.Windows.Forms.PaintEventArgs)
        '...

        e.Handled = True
    End Sub

End Class
Now you must add a LabelEx object to your form instead of a regular Label.
 
Last edited:
Back
Top