WithEvents
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.
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.
Module
We have a nested class
EventClass
that contains an Event called TestEvent
. The Sub
RaiseEvents
also is present in EventClass
.
EventClassInstance
is a special variable on the Module
. We create an instance of the EventClass
.TestEvent
that is present inside the EventClassInstance
variable.Module Module1 ' 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...") End Sub Sub PrintTestMessage2() Handles EventClassInstance.TestEvent ' This method also handles the event. Console.WriteLine("Test Message 2 Being Printed...") End Sub Sub Main() ' Call into the Event class and raise the test events. EventClassInstance.RaiseEvents() End Sub Class EventClass Public Event TestEvent() Sub RaiseEvents() ' Raise the Test event. ' ... This needs to be part of the class with the Event. RaiseEvent TestEvent() End Sub End Class End ModuleTest Message Being Printed... Test Message 2 Being Printed...
There is a clear advantage of WithEvents
-style syntax in VB.NET. We can add new event handlers (like PrintTestMessage2
) without calling AddHandler
.
Sub
itself.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.