如何从VB.NET中的控件中删除所有事件处理程序

时间:2014-06-03 21:55:55

标签: c#-to-vb.net

我找到了这个非常有用的代码here。我试图将它翻译成VB.NET,但我无法做到。我想删除活动的所有处理程序'点击'一个已知的按钮。

有人可以帮助我并将其翻译成VB.NET吗?

 public partial class Form1 : Form
 {
    public Form1()
    {
        InitializeComponent();

        button1.Click += button1_Click;
        button1.Click += button1_Click2;
        button2.Click += button2_Click;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Hello");
    }

    private void button1_Click2(object sender, EventArgs e)
    {
        MessageBox.Show("World");
    }

    private void button2_Click(object sender, EventArgs e)
    {
        RemoveClickEvent(button1);
    }

    private void RemoveClickEvent(Button b)
    {
        FieldInfo f1 = typeof(Control).GetField("EventClick", 
            BindingFlags.Static | BindingFlags.NonPublic);
        object obj = f1.GetValue(b);
        PropertyInfo pi = b.GetType().GetProperty("Events",  
            BindingFlags.NonPublic | BindingFlags.Instance);
        EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
        list.RemoveHandler(obj, list[obj]);
    }
}

}

1 个答案:

答案 0 :(得分:0)

这是根据OP请求直接转换为VB语法。

Imports System.Reflection    ' Required if not already in your code
Imports System.ComponentModel

Partial Public Class Form1
    Inherits Form

    Public Sub New()
        InitializeComponent()

        AddHandler button1.Click, AddressOf button1_Click
        AddHandler button1.Click, AddressOf button1_Click2
        AddHandler button2.Click, AddressOf button2_Click
    End Sub

    Private Sub button1_Click(sender As Object, e As EventArgs)
        MessageBox.Show("Hello")
    End Sub

    Private Sub button1_Click2(sender As Object, e As EventArgs)
        MessageBox.Show("World")
    End Sub

    Private Sub button2_Click(sender As Object, e As EventArgs)
        RemoveClickEvent(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
End Class

它工作正常,前提是表单上有button1button2。 让人们拒绝你的问题的事情(除了@phaedra的完全有效的评论)是这个代码没有什么意义。可以使用函数RemoveHandler

相关问题