Is it possible in VB.NET to easily write an event handler that will handle every event that fires? I’m wondering if one could make a logging system using something like this.
I’m wanting to do something like (in pseudocode):
Public Sub eventHandledEvent(ByVal sender As Object, ByVal e As EventArgs)
File.Write(sender.EventName)
End Sub
I realize it would be slow, but it wouldn’t be for a production system, only as a development tool.
You can do this with reflection. Here’s how. Create a form with a textbox called
TextBox1. Paste the following code. Run the project and look at the immediate window.This is from Francesco Balena’s book Programming Microsoft Visual Basic 2005 The Language. The techique works with any object that raises events, not just controls. It uses contravariance.
If you buy the book, there’s a full explanation and some more code which will allow you to identify which event has fired in the universal handler, and use regular expressions to handle only a subset of events. I don’t feel I can post such a long excerpt here.