Mandalorian
Mandalorian

Reputation: 333

How to remove all event handlers from a control in VB.NET

I found this very interessting Code here. I tried to translate it to VB.NET, but I am not able to. I want to remove all Handlers for the event 'click' of a known button.

Can anybody help me and translate it to 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]);
    }
}

}

Upvotes: 1

Views: 7940

Answers (1)

Grim
Grim

Reputation: 672

This is a direct translation into VB syntax, as per the OPs request.

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

It works fine, provided of course the form has button1 and button2 dropped onto it. The thing that makes people reject your question (aside from @phaedra 's perfectly valid comments) is that there is little point in this code. The function RemoveHandler can be used instead.

Upvotes: 1

Related Questions