C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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 Module
Output
Test Message Being Printed...
Test Message 2 Being Printed...
So: There is less overhead for adding new event handlers. We just need to add the Sub itself.