Visual Basic Concepts
Adding Events to a Class
Okay, let's say you've created a dinosaur simulation, complete with Stegosaur, Triceratops, and Tyrannosaur classes. As the final touch, you want the Tyrannosaur to roar, and when it does you want every other dinosaur in your simulation to sit up and take notice.
If the Tyrannosaur class had a Roar event, you could handle that event in all your other dinosaur classes. This topic discusses the declaration and handling of events in your class modules.
Note Kids, don't try this at home, at least with more than a few dinosaurs. Connecting every dinosaur with every other dinosaur using events could make your dinosaurs so slow that mammal objects would take over the simulation.
Properties and methods are said to belong to incoming interfaces, because they're invoked from outside the object. By contrast, events are called outgoing interfaces, because they're initiated within the object, and handled elsewhere.
The following topics describe the process of declaring, raising, and handling events, with examples.
Declaring and Raising Events Like procedures, events (and their arguments) have to be declared. In order for a declared event to occur, the object must raise it.
Handling an Object's Events The events your objects raise can be handled by other objects using variables declared using the WithEvents keyword.
Comparing WithEvents to Control Events on Forms Similarities and differences between event procedures associated with WithEvents variables and those associated with controls on forms.
Adding an Event to a Form A short step by step example of adding a custom event to a form.
Summary of Declaring, Raising, and Handling Events A summary of the process of using events in classes.
For More Information Creating ActiveX Components, in the Component Tools Guide provided with the Professional and Enterprise editions, discusses the use of events in designing your own software components.
For a discussion of a better way to handle dinosaurs, see "Polymorphism" later in this chapter.