Share via


When Do You Need to Create a Custom Event?

In many cases, it is not necessary to create a custom event — you can call a procedure to do the same thing. On the other hand, creating an event for a custom object can improve the object's flexibility and reusability. If you call a method rather than raising an event, the method will run the same way every time, no matter what code is working with the object. If you raise an event, the programmer who's using the object can decide how to respond to the event and can use the same object in different scenarios. Imagine, for example, if a command button ran the same code every time the user clicked it, instead of providing an event procedure to run whatever code the programmer chooses. Command buttons would not be nearly as useful!

Here are some cases where you'll must create an event rather than use a procedure:

  • When you implement an interface in multiple classes, and you want to maintain common code within the class that provides the interface, but you also must provide some customization within each individual class.
  • When you want to trap the messages that Microsoft® Windows sends to an application. Windows messages are similar to events — Windows alerts an application when the application gets or loses the focus, for example, and the application can respond accordingly. In some cases you might want your Microsoft® Visual Basic® for Applications (VBA) code to take notice of certain Windows messages and respond to them. To do this you must employ an advanced technique called subclassing, which makes it possible for your VBA code to look at a window's messages and take some action before the window's normal code is called. You can correlate particular messages to custom events that you create in your code.
  • When two or more objects, components, or applications must know that an event has occurred in an instance of a class that both are aware of. When an event occurs for an instance of a class, every variable that points to that instance in memory is notified of the event, and any event procedure that is tied to that instance runs. For example, if you have two forms that both have a variable pointing to a single instance of a Timer object, and the Timer object has an event that occurs when the timer is stopped, both forms will be notified of the event and will run the corresponding event procedure if it exists.

See Also

Why Build Your Own Objects? | Basic Class Concepts | Creating Property Procedures | Creating Events and Event Procedures | Extending Objects Through Interfaces | Designing Object Models | Creating Custom Objects for Web Pages