Visual Basic Concepts
Although a UserControl object has a Font property, there are situations where you will need to implement a Font object of your own. For example, if you want to allow the end user of your control to select a font at run time, the standard Font property won't work.
Even though the Font property is exposed and can be set in the Properties window at design time or via code at run time, the font displayed on the user control doesn't change. This is because the control never receives notification that the property has changed; consequently, it never fires its Paint event.
To resolve this problem, you need to add your own StdFont object to the control. The StdFont object is exactly the same as the UserControl Font with one exception — it provides a FontChanged event. You need to declare it using the WithEvents keyword in order to expose the FontChanged event:
Private WithEvents mFont as StdFont
In the Initialize event of your user control, the following code creates an instance of the StdFont object and assigns it to the User Control's Font property:
Private Sub UserControl_Initialize() Set mFont = New StdFont Set UserControl.Font = mFont End Sub
To expose your Font to the outside world, you'll need a Property Let / Property Set pair:
Public Property Get Font() as StdFont Set Font = mFont End Property Public Property Set Font (mnewFont as stdFont) With mFont .Bold = mnewFont.Bold .Italic = mnewFont.Italic .Name = mnewFont.Name .Size = mnewFont.Size End With PropertyChanged "Font" End Property
Notice that this code uses With to set each property of the StdFont object individually: Simply assigning
mFont would only change the default Name property.
You'll also need to add code in the FontChanged event to reassign the StdFont object and to force a Paint event:
Private Sub mFont_FontChanged(ByVal PropertyName As String) Set UserControl.Font = mFont Refresh End Sub
Finally, in the Paint event you can add code to display text. The text will be displayed in the newly selected font.
Private Sub UserControl_Paint() Cls ' Clear the display Print "Hello" End Sub
Now the Font property of your user control can be set at either design time or at run time and the changes will immediately be visible.