ThN
ThN

Reputation: 3276

How to make an event empty again?

If you have an Winform MouseDown event set to a method, how do you empty or reset the event. so that it has no methods to call when it fires.

Take for instance:

MouseDown += new System.Windows.Forms.MouseEventHandler(@SelectMouseDown);

And you want to reset MouseDown event to nothing or nil or null.

I think I was eluded to do the following by some other StackOverflow question.

MouseDown -= System.Windows.Forms.MouseEventHandler(@SelectMouseDown);

It doesn't work.

Upvotes: 2

Views: 132

Answers (2)

Katu
Katu

Reputation: 701

Did not do any tests, but this should do the job. Add the "new" to start of the line

MouseDown -= new System.Windows.Forms.MouseEventHandler(@SelectMouseDown);

Upvotes: 2

JaredPar
JaredPar

Reputation: 754793

In this case you are consuming an event which is owned by another type. There is no way to completely clear the list of handlers. You can only remove handlers to which you have access to the equivalent delegate. Typically this is the set of handlers which you have added.

The code you've shown will remove the handler on MouseDown for SelectMouseDown. But it won't clear any others.

If you own the event then removing all handlers is as easy as setting the event to null.

private event EventHandler _mouseDownEvent;
public event EventHandler MouseDown {
  add { _mouseDownEvent += value; }
  remove { _mouseDownEvent -= value; }
}

void ClearMouseDown() {
  _mouseDownEvent = null;
}

Upvotes: 3

Related Questions