none
如何删除事件处理程序 RRS feed

  • 问题

  • 如题,我使用

    Public Event MessageRecieved As EventHandler
    

    新建了一个事件,并可以使用AddHandler和RemoveHandler创建或者删除事件,但这样还是不够灵活

    是否存在一种方法,如一个函数,删除所有的事件处理程序,使该事件立即没有处理程序?

    如以下函数,如果有,请问应该如何写?

        Public Sub ClearHandler()
    
        End Sub


    2011年11月29日 5:53

答案

  • 试试这段代码:

        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            RemoveClickEvent(Me.Button1)
        End Sub
    
        Private Sub RemoveClickEvent(b As Button)
            Dim f1 As FieldInfo = GetType(Control).GetField("EventClick", BindingFlags.[Static] Or BindingFlags.NonPublic)
            Dim obj As Object = f1.GetValue(b)
            Dim pi As PropertyInfo = b.[GetType]().GetProperty("Events", BindingFlags.NonPublic Or BindingFlags.Instance)
            Dim list As EventHandlerList = DirectCast(pi.GetValue(b, Nothing), EventHandlerList)
            list.[RemoveHandler](obj, list(obj))
        End Sub
    


    注意import

    Imports System.Reflection
    Imports System.ComponentModel
    

    希望有用。
     


    Mike Feng
    MSDN Community Support | Feedback to us
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    2011年12月1日 3:42
    版主

全部回复

  • 看到这个问题,我也忽然想到一个问题,同问一下,有什么方法可以找到一个事件的所有处理方法?
    --!
    2011年11月30日 7:55
  • 试试这段代码:

        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            RemoveClickEvent(Me.Button1)
        End Sub
    
        Private Sub RemoveClickEvent(b As Button)
            Dim f1 As FieldInfo = GetType(Control).GetField("EventClick", BindingFlags.[Static] Or BindingFlags.NonPublic)
            Dim obj As Object = f1.GetValue(b)
            Dim pi As PropertyInfo = b.[GetType]().GetProperty("Events", BindingFlags.NonPublic Or BindingFlags.Instance)
            Dim list As EventHandlerList = DirectCast(pi.GetValue(b, Nothing), EventHandlerList)
            list.[RemoveHandler](obj, list(obj))
        End Sub
    


    注意import

    Imports System.Reflection
    Imports System.ComponentModel
    

    希望有用。
     


    Mike Feng
    MSDN Community Support | Feedback to us
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    2011年12月1日 3:42
    版主