ActiveX Controls: The Definitive Guide, Page 3
For this example, rename the control ctlCaption. Draw a label on to the usercontrol and rename it lblCaption. Set its AutoSize property to True. Now add this code into the Usercontrol's Resize method:
Private Sub UserControl_Resize()
'--
'Resize the control based on the caption
'--
lblCaption.Move ScaleLeft, _
ScaleTop, _
lblCaption.Width, _
lblCaption.Height
If lblCaption.Width > 0 Then
UserControl.Width = lblCaption.Width
UserControl.Height = lblCaption.Height
End If
End Sub
The basis of this control is to act as a caption. At the moment you can't apply any of the Font, ForeColor or BackColor properties. We will now add code to the Let procedures to make them change the label. Here are the new property procedures:
Public Property Set Font( _
ByVal New_Font As Font)
Set lblCaption.Font = New_Font
PropertyChanged "Font"
End Property
Public Property Let ForeColor( _
ByVal New_ForeColor As OLE_COLOR)
lblCaption.ForeColor = New_ForeColor
PropertyChanged "ForeColor"
End Property
Public Property Let BackColor( _
ByVal New_BackColor As OLE_COLOR)
lblCaption.BackColor = New_BackColor
PropertyChanged "BackColor"
End Property
The property Get procedures also need to be ammended:
Public Property Get Font() As Font Set Font = lblCaption.Font End Property Public Property Get ForeColor() As OLE_COLOR ForeColor = lblCaption.BackColor End Property Public Property Get BackColor() As OLE_COLOR BackColor = lblCaption.BackColor End Property
Add a Standard EXE project and draw our control onto the form. Change the properties and watch the label change at the same time. But we are missing one thing. The ability to change the caption. Paste these two procedures in:
Property Get Caption() As String Caption = lblCaption.Caption End Property Property Let Caption(ByVal New_Caption As String) lblCaption.Caption = New_Caption PropertyChanged "Caption" End Property
We also need to change the WriteProperties and ReadProperties procedures:
Private Sub UserControl_ReadProperties(PropBag As PropertyBag)
lblCaption.BackColor = PropBag.ReadProperty("BackColor",&H8000000F)
lblCaption.ForeColor = PropBag.ReadProperty("ForeColor",&H80000012)
UserControl.Enabled = PropBag.ReadProperty("Enabled", True)
Set lblCaption = PropBag.ReadProperty("Font", Ambient.Font)
lblCaption.Caption = PropBag.ReadProperty("Caption","Caption Control")
End Sub
Private Sub UserControl_WriteProperties(PropBag As PropertyBag)
Call PropBag.WriteProperty("BackColor", lblCaption.BackColor,&H8000000F)
Call PropBag.WriteProperty("ForeColor", lblCaption.ForeColor,&H80000012)
Call PropBag.WriteProperty("Enabled", UserControl.Enabled,True)
Call PropBag.WriteProperty("Font", lblCaption.Font,Ambient.Font)
Call PropBag.WriteProperty("Caption", lblCaption.Caption,"Caption Control")
End Sub
There you have your first activex control.
In the next part we will discuss events and how you can make a better control.
