VB.NET WithEvents: Handles and RaiseEventUse the Handles keyword with WithEvents and RaiseEvent. Implement event handling.
This is a special syntax for events in VB.NET. We can add events with the Handles keyword. We do not need to ever call AddHandler or wire up events.Event
With the WithEvents keyword, we specify a class that contains an event. Then we can use Handles to handle the events in that class. This is powerful.
An example program.
Consider this Module. We have a nested class EventClass that contains an Event called TestEvent. The Sub RaiseEvents also is present in EventClass.Sub
WithEvents: This is a special variable on the Module. We create an instance of the EventClass.
Subs: We have 2 Subs that both use the Handles keyword. They handle the TestEvent that is present inside the EventClassInstance variable.
VB.NET program that uses WithEvents, Handles
' An instance of the Event class.
WithEvents EventClassInstance As New EventClass
Sub PrintTestMessage() Handles EventClassInstance.TestEvent
' This method handles the TestEvent.
Console.WriteLine("Test Message Being Printed...")
Sub PrintTestMessage2() Handles EventClassInstance.TestEvent
' This method also handles the event.
Console.WriteLine("Test Message 2 Being Printed...")
' Call into the Event class and raise the test events.
Public Event TestEvent()
' Raise the Test event.
' ... This needs to be part of the class with the Event.
Test Message Being Printed...
Test Message 2 Being Printed...
Notes, an advantage.
There is a clear advantage of WithEvents-style syntax in VB.NET. We can add new event handlers (like PrintTestMessage2) without calling AddHandler.
So: There is less overhead for adding new event handlers. We just need to add the Sub itself.
A summary. We handled events with the Handles keyword in VB.NET. This syntax form has some advantages over AddHandler—we do not need to use a statement to add each new handler.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.