You've probably noticed some similarities between the way you use WithEvents variables and the way you handle the events raised by controls on a form. In both cases, when you select the event in the right-hand drop down of a code window, you get an event procedure containing the correct arguments for the event.
In fact, the mechanism is exactly the same. A control is treated as a property of the form class, and the name of that property is the value you assigned to the control's Name property in the Properties window.
It's as if there's a Public module-level variable with the same name as the control, and all of the control's event procedure names begin with that variable name, just as they would with a WithEvents variable.
You can easily see this by declaring the variable mWidget
Public instead of Private. The moment you do this, mWidget
will show up in the Object Browser as a property of Form1, just like the controls on the form.
The difference between the two cases is that Visual Basic automatically creates instances of all the controls on a form when the form is created, whereas you have to create your own instances of classes whose events you want to handle, and assign references to those objects to WithEvents variables.
For More Information You can add your own events to forms, as discussed in "Adding an Event to a Form."