You can use Delegate.RemoveAll(). (The part that interests you is in button2_Click)
public void Form_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
button1.Click += new EventHandler(button1_Click);
button2.Click += new EventHandler(button2_Click);
TestEvent += new EventHandler(Form_TestEvent);
}
event EventHandler TestEvent;
void OnTestEvent(EventArgs e)
{
if (TestEvent != null)
TestEvent(this, e);
}
void Form_TestEvent(object sender, EventArgs e)
{
MessageBox.Show("TestEvent fired");
}
void button2_Click(object sender, EventArgs e)
{
Delegate d = TestEvent as Delegate;
TestEvent = Delegate.RemoveAll(d, d) as EventHandler;
}
void button1_Click(object sender, EventArgs e)
{
OnTestEvent(EventArgs.Empty);
}
You should notice that it does not change the contents of the delegates that you pass it to it, it returns the changed delegate. Therefore, you will not be able to change events on the button that you dropped on the form from the form, because it button1.Clickcan only use +=or -=, and not =. This will not compile:
button1.Click = Delegate.RemoveAll(d, d) as EventHandler;
, , , , . - , , !