views:

29

answers:

1

I've been thinking about my options when it comes to events in vb.net. What I'd like to do is to track events that are fired in an application without explicitly declaring them with 'handles' sub. Here is a pseudo-code:

Private Sub HandlesAllEvents(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles all.events
    Select Case sender
        Case button1
            If event = click Then
              doSomething()
            End If
    End Select
End Sub

Yeah I know, not quite working, but is there any way of implementing something like this in vb.net? My end game is really to be able to monitor events fired in many objects from another object, isn't there a more maintainable way to do that then to add a special sub in each object that handles the event that I want to catch?

I need some way to let one object handle events fired in other objects without a special sub, the AddHandler goes a long way, but I can't really use that dynamically like so:

Public Sub AddEvent(event as System.EventArgs)
    AddHandler event AddressOf doSomething()
End Sub

Which would be called with:

Objec.AddEvent(form1.button1.Click)

Am I making any sense here? Do you know what I'm talking about? Do you know how to do this? Any help appreciated!

A: 

Forewords: I don't think it's a good idea, your HandlesAllEvents would me full of conditional expressions. I think the less IFs in a program, the better it is for the sake of maintenance. Less IFs means the designer made a good job using object oriented paradigms, design patterns and design good practices :)

That said, it is a different case when you want to write less code (thus improving maintenance) and handle the same event for multiple similar controls, which also behave similarly. For example if you have a set of text boxes and you want to have the focused one change its background color to be more visible. Then you encapsulate the GotFocus (and LostFocus) handler code in a single method.

If you still want to do that :) then you could use reflection to discover all the controls in your application, and for each control all the events it can raise, and then SetHandler to your big method.

vulkanino