Visual Basic Concepts

Adding Events to Classes

You can add events to any class in your component. Events declared in classes provided by your component can be handled by clients regardless of whether your component is running in process or out of process. All events are public.

You declare an event using the Event keyword:

Event SomethingHappened(   ByVal HowMuch As Double, _
      ByVal When As Date)

Note   You can declare event arguments just as you do arguments of procedures, with the following exceptions: Events cannot have named arguments, optional arguments, or ParamArray arguments. Events do not have return values.

You raise the event from within your class module’s code, whenever the circumstances that define the event occur.

   If blnSomethingHappened Then
      RaiseEvent SomethingHappened(dblPriceIncrease, _
         Now)
   End If

When the event is raised in an instance of the class, code in the SomethingHappened event procedures of any clients that are handling the event for that particular object will be executed. Events must be handled on an object-by-object basis; a client cannot elect to handle an event for all currently existing objects of a particular class.

If multiple clients have references to the same object, and are handling an event it raises, control will not return to your component until all clients have processed the event.

You can allow clients to respond to events by declaring a parameter ByRef instead of ByVal. This allows any client to change the value of the argument. When execution resumes, on the line after RaiseEvent, you can examine the value of this argument and take appropriate action.

This capability is frequently used for Cancel arguments, as with the QueryUnload event of Visual Basic forms.

Note   Visual Basic raises a separate QueryUnload event for each form; if one form cancels the event, events for subsequent forms are not raised.

Events can be used instead of call-back functions, as discussed in "Building Code Components." The capabilities of the two approaches are identical, but implementation of events is much simpler, for you and for the user of your component.

Events cannot be handled within the class that declared them.

For More Information*   Raising events in controls is discussed in detail in "Building ActiveX Controls." The syntax for raising and handling events is covered in "Adding Events to a Class" in "Programming with Objects," in the *Visual Basic Programmer’s Guide.