Thursday, April 28, 2011

WinForms: temporarily disable an event handler

How can I disable an event handler temporarily in WinForms?

From stackoverflow
  • Probably, the simplest way (which doesn't need unsubscribing or other stuff) is to declare a boolean value and check it at the beginning of the handler:

    bool dontRunHandler;
    
    void Handler(object sender, EventArgs e) {
       if (dontRunHandler) return;
    
       // handler body...
    }
    
  • Disable from what perspective? If you want to remove a method that's in your scope from the list of delegates on the handler, you can just do..

    object.Event -= new EventHandlerType(your_Method);
    

    This will remove that method from the list of delegates, and you can reattach it later with

    object.Event += new EventHandlerType(your_Method);
    
    Jon Skeet : I think you mean your_Method instead of your_Method(). As of C# 2.0, you also don't need the "new EventHandlerType" part - just object.Event += yourMethod; and object.Event -= yourMethod;
    Adam Robinson : Yep, I meant for it to be sans parens ;). Was not aware of the implicit delegate construction, though; that's good to know.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.