The following step by step procedure shows how you can create custom events for forms. To try this exercise, open a new Standard Exe project and do the following:
To add an event to Form1
Public Property Get Form1() As Form1
Set Form1 = mForm1
End Property
Public Property Set Form1(ByVal NewForm1 As Form1)
Set mForm1 = NewForm1
End Property
If you're using Procedure View, the property procedures can't be viewed at the same time. Click the Full Module View button at the bottom left corner of the code window to switch to Full Module View. You can return to Procedure View by clicking the Procedure View button next to it. (Hover the mouse over the buttons to see which is which.)
Event Gong
Private mc1 As Class1
Now that Class1 has been created, it's possible to create a variable of type Class1. This procedure switches between Form1 and Class1 several times, because a step in one module requires first adding code to the other.
Private WithEvents mForm1 As Form1
As discussed in "Adding Events to a Class," the WithEvents keyword means this instance of Form1 is associated with events. Note that this step wasn't possible until the Gong event had been created.
Private Sub mForm1_Gong()
MsgBox "Gong!"
End Sub
Private Sub Form_Load()
Set mc1 = New Class1
Set mc1.Form1 = Me
End Sub
The first line creates a Class1 object, and the second assigns to its Form1 property (created in step 1) a reference to Form1 (that is, Me — when you're in Form1's Code window, Me refers to Form1; when you're in Class1's Code window, Me refers to Class1).
Private Sub Text1_Change()
RaiseEvent Gong
End Sub
Each time the contents of a text box change, the form's Gong event will be raised.
As shown in "Declaring and Raising Events," you can add arguments to events. For example, you might pass the name of the control — or better still, a reference to the control — to the receiver of the event.