Detect when a new control is added to an ActiveX container

You can easily create ActiveX controls that work as containers for other controls, by setting their ControlContainer property to True. However, VB doesn’t offer any event for detecting when the programmer adds or remove controls to the ActiveX control, after placing it on a form’s surface.

It’s pretty easy to detect such actions with the aid of a Timer control, though. Just place a Timer control on the UserControl’s surface, set its Interval property to a suitable value (for example, 500 milliseconds) and then add the following code:

Private Sub Timer1_Timer()    Static ctrlCount As Integer        If ctrlCount <> ContainedControls.Count Then        ctrlCount = ContainedControls.Count        ' a new control has been added or removed        ' from inside your UserControl        '        ' ...add your code here........        '    End IfEnd Sub

If you’re working under VB6 you can add the Timer control dynamically, so it’s just a matter of copying-and-pasting the following code:

Dim WithEvents tmrNotifier As TimerPrivate Sub UserControl_Initialize()    ' create a new Timer control dynamically    Set tmrNotifier = Controls.Add("VB.Timer", "tmrNotifier")    tmrNotifier.Interval = 500End SubPrivate Sub tmrNotifier_Timer()    Static ctrlCount As Integer        If ctrlCount <> ContainedControls.Count Then        ctrlCount = ContainedControls.Count        ' a new control has been added or removed        ' from inside your UserControl        '        ' ...add your code here........        '    End IfEnd Sub

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: