Handle ALL events in one handler?

Is it possible in VB.NET to easily write an event handler that will handle every event that fires? I am wondering if it is possible to make a registration system using something like this.

I want to do something like (in pseudocode):

Public Sub eventHandledEvent(ByVal sender As Object, ByVal e As EventArgs) File.Write(sender.EventName) End Sub 

I understand that this will be slow, but it will not be for the production system, only as a development tool.

+4
source share
2 answers

You can do this with reflection . Here is how. Create a form with the TextBox1 text box. Paste the following code. Run the project and look at the nearest window.

 Public Class Form1 Private Sub Form1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated RegisterAllEvents(TextBox1, "MyEventHandler") End Sub Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs) Debug.WriteLine("An event has fired: sender= " & sender.ToString & ", e=" & e.ToString) End Sub Sub RegisterAllEvents(ByVal obj As Object, ByVal methodName As String) 'List all events through reflection' For Each ei As System.Reflection.EventInfo In obj.GetType().GetEvents() Dim handlerType As Type = ei.EventHandlerType Dim method As System.Reflection.MethodInfo = Me.GetType().GetMethod(methodName) 'Create a delegate pointing to the method' Dim handler As [Delegate] = [Delegate].CreateDelegate(handlerType, Me, method) 'Register the event through reflection' ei.AddEventHandler(obj, handler) Next End Sub End Class 

This is from the book Francesco Balena Programming Microsoft Visual Basic 2005 Language . A technician works with any object that triggers events, not just controls. He uses contravariance .

If you buy a book , you get a full explanation and another code that allows you to determine which event was issued in the universal handler and use regular expressions to process only a subset of events. I don’t feel that I can publish such a long passage.

+4
source

Edit: Corrected due to Hans comment.

There is no problem, at least for some events, as it is already built-in for events sending messages. Just take a look at Control.WndProc . All messages in the window will pass there.

+3
source

Source: https://habr.com/ru/post/1316202/


All Articles