Determine if an event has been attached to yet

前端 未结 4 1132
悲哀的现实
悲哀的现实 2021-01-12 07:12

I have two objects - one that contains some code with will fire an event, and one that contains the handler for that event. I can\'t \"AddHandler\" in the Load of the first

相关标签:
4条回答
  • 2021-01-12 07:19

    If you just want to know whether any handler has been attached, you should be able to check whether the event is null.

    if (MyButton.Click == null)
    {
        MyButton.Click += myEventHandler;
    }
    

    (I'll let you translate that into VB)

    0 讨论(0)
  • 2021-01-12 07:22

    According to the responses here: http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/9ec8ff1c-eb9b-4cb3-8960-9cd4b25434f2 (which seem to work according to my testing), a check for existing event handlers is done upon calling RaiseEvent. If you do not want to raise an event and just need to check to see if any handlers are attached, you can check the value of a hidden variable called <your_event_name>Event like:

    Public Event Foo As ActionFoo
    
    If FooEvent IsNot Nothing Then...
    
    0 讨论(0)
  • 2021-01-12 07:34

    VB.Net creates a special private member variable in the pattern of <YourEvent>Event that you can then use to test against Nothing.

    Public Event MyClick As EventHandler
    
    Private Sub OnMyClick()
        If MyClickEvent IsNot Nothing Then
            RaiseEvent MyClick(Me, New EventArgs())
        Else
            ' No event handler has been set.
            MsgBox("There is no event handler. That makes me sad.")
        End If
    End Sub
    

    http://blogs.msdn.com/b/vbteam/archive/2009/09/25/testing-events-for-nothing-null-doug-rothaus.aspx

    0 讨论(0)
  • 2021-01-12 07:46

    You could also just have a bool field that you check before hooking the event.

    if not eventHooked then
     addhandler
     eventHooked = true
    end if
    

    Also if you need a good c# to vb converter http://www.tangiblesoftwaresolutions.com/ has one that can translate a 100 lines on the fly or less for or translate a project of a 1000 lines for free. More than that you have to purchase it, but that usually those limits will work just fine. No I am not trying to advertise for them :-)

    0 讨论(0)
提交回复
热议问题