Its quite easy in VB.
Step one - add a container control like a PictureBox
Code:
Dim pContainer As VB.PictureBox
Set pContainer = Me.Controls.Add("VB.PictureBox", "picContainer" , Me)
Step two add the control
Code:
Dim pLabel As VB.Label
Set pLabel = Me.Controls.Add("VB.Label", "lblLabel", pContainer)
pLabel.Visible = True
The last parameter on the Add method for Controls is a reference to the container control you're adding this to. If its an OCX you're making then replace "Me" with "UserControl" in the adding container code. Also, all added controls are invisible by default so make then visible
The hard part is VB has no easy way of catching events from these controls, so we need a few extra steps.
Step three - add a class module to control each type of control you add - in this case Labels. The gControls bit will be explained later
Code:
Option Explicit
Private WithEvents mControl As VB.Label
Public Property Get Control() As Control
Set Control = mControl
End Property
Public Property Set Control(ByRef Value As Control)
Set mControl = Value
End Property
Private Sub mControl_Click()
Call gControls.lblLabel_Click(mControl)
End Sub
Step Four - create a new instance of this class for each object you wish to control and add it to a collection.
Code:
Private mControls As Collection
Private Sub ControlLabel(ByRef Control As VB.Label)
Dim pControl As lblLabel
Set pControl = New lblLabel
Set pControl.Control = Control
mControls.Add pControl, Control.Name
Set pControl = Nothing
End Sub
Call ControlLabel(pLabel)
Step Five - create a global reference to a form/object/whatever that handles the control events. In this case a form
Code:
' Global module somewhere
Public gControls as frmControls
Set gControls = new frmControls
Code:
'frmControls
Public Sub lblLabel_Click(ByRef Label As VB.Label)
Debug.Print "You clicked label " & Label.Name
End Sub
IMPORTANT!!!!!
If you remove the controls its easiet to just remove the container - saves having to remove each control itself
If you remove any control, you MUST remove its control class from the collection as well otherwise VB will explode
HTH
