tags:

views:

678

answers:

2

How can I disable an event handler temporarily in WinForms?

+8  A: 

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...
}
Mehrdad Afshari
+8  A: 

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);
Adam Robinson
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;
Jon Skeet
Yep, I meant for it to be sans parens ;). Was not aware of the implicit delegate construction, though; that's good to know.
Adam Robinson