If you set a user control's ControlContainer property to True, objects drawn on top of that control can be moved and resized as a group. The Microsoft Tabbed Dialog and DataRepeater controls are two examples of container controls that ship with Visual Basic. Figure 6-17 shows a simple container control created in Visual Basic using Shape and Label controls to create a frame.
Figure 6-17. The Containr sample control's ControlContainer property is True, so it mimics the behavior of a Frame control.
The code for the Containr control (Containr.VBP) handles resizing the frame as shown below:
`User interaction section
Private Sub UserControl_Resize()
`Resize the frame to match control
shpFrame.Width = UserControl.ScaleWidth - shpFrame.Left
shpFrame.Height = UserControl.ScaleHeight - shpFrame.Top
End Sub
The Containr control's caption is initialized using the Extender object, which gives access to the built-in properties that Visual Basic and other control containers provide to all objects. The Extender object is available to the InitProperties procedure, but will cause an error if you try to access it earlier in the control's life-cycle, such as from the control's Initialize event. The following code displays the control name that Visual Basic automatically assigns when a user creates an instance of the control on a form:
`Control maintenance section
Private Sub UserControl_InitProperties()
`Display appropriate caption
lblTitle.Caption = Extender.Name
End Sub
The Caption property sets and returns the caption displayed in lblTitle. This property is Read/Write and available at design time, so it has Property Let and Get procedures as well as code in the ReadProperties and WriteProperties event procedures, as shown below.
Private Sub UserControl_ReadProperties(PropBag As PropertyBag)
lblTitle.Caption = PropBag.ReadProperty("Caption")
End Sub
Private Sub UserControl_WriteProperties(PropBag As PropertyBag)
PropBag.WriteProperty "Caption", lblTitle.Caption
End Sub
`Properties section
Public Property Get Caption() As String
Caption = lblTitle.Caption
End Property
Public Property Let Caption(Setting As String)
lblTitle.Caption = Setting
End Property
The Controls property returns the collection of controls contained in the Containr control. This is the only feature you don't get with the standard Frame control, and it is included with this example to show you how to use the ContainedControls collection. The ContainedControls collection is created by Visual Basic when you set ControlContainer to True; it is not available on other types of controls. The following code shows the definition for the read-only Controls property:
`Read-only property
Public Property Get Controls() As Collection
Set Controls = UserControl.ContainedControls
End Property