How to delete an event handler

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dom

    How to delete an event handler

    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

  • Marc Gravell

    #2
    Re: How to delete an event handler

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

    void SomeHandler(obj ect sender, KeyPressEventAr gs e) {...}

    then you can use:

    t.KeyPress -= SomeHandler;
    or (identical)
    t.KeyPress -= new KeyPressEventHa ndler(SomeHandl er);

    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:

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

    Marc


    Comment

    • Sebastian Lopez

      #3
      Re: How to delete an event handler

      Dom,

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

      public EventHandler MyEvent;
      foreach (EventHandler eventHandler in
      MyEvent.GetInvo cationList())
      {
      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...@g mail.comwrote:
      You can only remove event-handlers that you know about. For example, if you
      have:
      >
      void SomeHandler(obj ect sender, KeyPressEventAr gs e) {...}
      >
      then you can use:
      >
      t.KeyPress -= SomeHandler;
      or (identical)
      t.KeyPress -= new KeyPressEventHa ndler(SomeHandl er);
      >
      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:
      >
      KeyPressEventHa ndler handler = (sender, e) ={}
      t.KeyPress += handler;
      //...
      t.KeyPress -= handler;
      >
      Marc

      Comment

      Working...