Declaring Objects with the WithEvents Keyword

By default, when you declare a variable for an object that exposes events, Visual Basic cannot see those events. This is also the case of the previous section’s example, where you declare a Timer and then need to explicitly register for event handling. A solution to this scenario is to declare an object with the WithEvents keyword that makes events visible to Visual Basic. Thanks to WithEvents, you do not need to register for events, and you can take advantage of the Handles clause to specify what event a method is going to handle. The code in Listing 15.2 demonstrates this, providing a revisited version of the EventsDemo class.

Listing 15.2 Catching Events with WithEvents and Handles

Notice that ...

Get Visual Basic® 2010 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.