While helping some Windows API folks with some sample code this week, I stumbled upon…uh…I mean “carefully researched” an issue that you might find handy.
You may be aware that the RaiseEvent statement automatically checks to verify if an event handler exists before raising the event. If the event is Nothing, then there’s no event handler and RaiseEvent terminates. If the event is not Nothing, then RaiseEvent triggers the event.
However, what if you want to follow a different code path if the event is Nothing? Unfortunately, the RaiseEvent statement doesn’t return a value that could indicate whether the event was fired. So, what’s a developer to do?
The answer? When the VB compiler sets up your event, it creates a private variable for the event in the form of <event name>Event. So, if I set up an event named TriggerMe, the VB compiler creates an event variable named TriggerMeEvent. You can test this variable for Nothing. It’s as simple as that! (Note: You won’t see this variable using Intellisense, but you can find it when debugging or through reflection.)
Here’s a quick example:
Public Event SolutionFound As EventHandler
Private Sub OnSolutionFound()
If SolutionFoundEvent IsNot Nothing Then
RaiseEvent SolutionFound(Me, New EventArgs())
‘ No event handler has been set.
MsgBox(“There is no event handler. That makes me sad.”)