By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,906 Members | 1,767 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,906 IT Pros & Developers. It's quick & easy.

How to delete an event handler

P: n/a
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

Mar 20 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Mar 20 '08 #2

P: n/a
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

On Mar 20, 11:41 am, "Marc Gravell" <marc.grav...@gmail.comwrote:
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
Mar 20 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.