An object that raises events is called an event source. To handle the events raised by an event source, you can declare a variable of the object's class using the WithEvents keyword.
This topic continues the Widget object example begun in "Declaring and Raising Events." To handle the PercentDone event of a Widget, place the following code in the Declarations section of Form1:
Private WithEvents mWidget As Widget
Private mblnCancel As Boolean
The WithEvents keyword specifies that the variable mWidget will be used to handle an object's events. You specify the kind of object by supplying the name of the class from which the object will be created.
The variable mWidget is declared in the Declarations section of Form1 because WithEvents variables must be module-level variables. This is true regardless of the type of module you place them in.
The variable mblnCancel will be used to cancel the LongTask method.
Limitations on WithEvents Variables
You should be aware of the following limitations on the use of WithEvents variables:
A WithEvents variable cannot be a generic object variable. That is, you cannot declare it As Object — you must specify the class name when you declare the variable.
You cannot declare a WithEvents variable As New. The event source object must be explicitly created and assigned to the WithEvents variable.
You cannot declare WithEvents variables in a standard module. You can declare them only in class modules, form modules, and other modules that define classes.