How to delete an event handler

D

Dom

For various reasons, I need to remove the event handlers for a given
event. The event can only appear on the left side of "+=" or "-=", so
I'm not sure how this is done.

I tried this:

while (t.KeyPress != null) t.KeyPress--;

but the compiler won't accept it. Any ideas?

Dom
 
M

Marc Gravell

You can only remove event-handlers that you know about. For example, if you
have:

void SomeHandler(object sender, KeyPressEventArgs e) {...}

then you can use:

t.KeyPress -= SomeHandler;
or (identical)
t.KeyPress -= new KeyPressEventHandler(SomeHandler);

if you have used an anomymous function/lambda, then you'll need to cache the
delegate instance prior to subscribing, and unsubscribe with the same:

KeyPressEventHandler handler = (sender, e) => {}
t.KeyPress += handler;
//...
t.KeyPress -= handler;

Marc
 
S

Sebastian Lopez

Dom,

You can remove all the event handlers with the following code:

public EventHandler MyEvent;
foreach (EventHandler eventHandler in
MyEvent.GetInvocationList())
{
MyEvent -= eventHandler;
}

In this snippet, you can use the -= operator as you get a reference to
each handler suscribed to the event. In the other hand, operator --
cannot be used with events.

I hope it helps,
Seba
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top