How can I disable an event handler temporarily in WinForms?
An event handler, in C#, is a method that contains the code that gets executed in response to a specific event that occurs in an application. Event handlers are used in graphical user interface (GUI) applications to handle events such as button clicks and menu selections, raised by controls in the user interface.
Event handler code can be made to run when an event is triggered by assigning it to the target element's corresponding onevent property, or by registering the handler as a listener for the element using the addEventListener() method.
Form event handlers define a unit of work to be performed in response to an event. Event handlers are defined for specific forms. They are not shared across forms.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With