Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinForms: temporarily disable an event handler

Tags:

c#

winforms

How can I disable an event handler temporarily in WinForms?

like image 962
George Avatar asked Apr 13 '09 16:04

George


People also ask

What is C# Eventhandler?

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.

What can trigger execution of the event handler?

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.

What is the usage of event handlers in form applications?

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.


2 Answers

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... } 
like image 60
mmx Avatar answered Oct 13 '22 00:10

mmx


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); 
like image 43
Adam Robinson Avatar answered Oct 12 '22 23:10

Adam Robinson