Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all event handlers from an event

To create a new event handler on a control you can do this

c.Click += new EventHandler(mainFormButton_Click); 

or this

c.Click += mainFormButton_Click; 

and to remove an event handler you can do this

c.Click -= mainFormButton_Click; 

But how do you remove all event handlers from an event?

like image 329
Carrick Avatar asked Sep 18 '08 11:09

Carrick


People also ask

How do I remove all event listeners?

To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.

Should you always remove event listeners?

TLDR; Always remove event listeners when you don't plan on using them any longer.

How do I remove event listener from click?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.


2 Answers

I found a solution on the MSDN forums. The sample code below will remove all Click events from button1.

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]);     } } 
like image 103
xsl Avatar answered Nov 07 '22 01:11

xsl


You guys are making this WAY too hard on yourselves. It's this easy:

void OnFormClosing(object sender, FormClosingEventArgs e) {     foreach(Delegate d in FindClicked.GetInvocationList())     {         FindClicked -= (FindClickedHandler)d;     } } 
like image 37
Stephen Punak Avatar answered Nov 07 '22 01:11

Stephen Punak