Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find out if a particular delegate has already been assigned to an event?

I have a command button on a winform. So, if I have something like:

myButton.Click += MyHandler1;
myButton.Click += MyHandler2;
myButton.Click += MyHandler3;

How can I tell if any particular MyHandler has already been added to the Click event so it doesn't get added again somewhere else in my code?

I've read how you can use GetInvocationList() for your own event's information. But I get errors when trying to get the items for my command button using various combinations. It says,

"The event 'System.Windows.Forms.Control.Click' can only appear on the left hand side of += or -=."

What am I missing?

[Edit] - I'd like to accentuate this question that Ahmad pointed out. It's a kludge and should be easier IMHO, but it looks like it might just work.

like image 832
IAmAN00B Avatar asked Nov 04 '10 02:11

IAmAN00B


People also ask

How do I find an event handler?

If you are looking to see if a specific handler (function) has been added then you can use array. You can examine various properties on the Method property of the delegate to see if a specific function has been added. If you are looking to see if there is just one attached, you can just test for null.

What is an event and a delegate ?- How are they related?

Delegate is a type that defines a signature and holds a reference of method whose signature matches with the delegate. Event is a notification raised by an object to signal the occurrence of an action. Delegate is associated with the event to hold a reference of a method to be called when the event is raised.

What is the difference between event and delegate?

An event is declared using the event keyword. Delegate is a function pointer. It holds the reference of one or more methods at runtime. Delegate is independent and not dependent on events.

How events are handled through delegates?

Using Delegates with EventsThe events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class.


1 Answers

If you're in doubt if your handler is already added then just remove it and add it again. If your handler wasn't added in the first place, your removal is just ignored.

myButton.Click -= MyHandler1;
myButton.Click += MyHandler1;

You could also create one method for attaching to an event, and make sure that the code is only run once.

private bool handlersAdded;
private void AddHandlers()
{
    if (this.handlersAdded) return;
    myButton.Click += MyHandler1;
    this.handlersAdded = true;
}
like image 71
Paw Baltzersen Avatar answered Oct 13 '22 10:10

Paw Baltzersen