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.
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.
Info EventClassInstance is a special variable on the Module. We create an instance of the EventClass.
Here We have 2 Subs that both use the Handles keyword. They handle the TestEvent that is present inside the EventClassInstance variable.
' 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.RaiseEvent TestEvent()
End ModuleTest 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 10, 2023 (edit).