How do I figure out if a particular client object has subscribed to one of my events?

Platform: WinForms| Category: Events

In C#, you can do as follows:


		// In a Control derived class, for example, first store the handlers in a custom list.
		private EventHandler myHandlers;
		public new event EventHandler Click
		{
			add
			{
				this.myHandlers += value;
			}
			remove
			{
				this.myHandlers -= value;
			}
		}

		// This method will specify whether a particular delegate is subscribed.
		public bool IsSubscribed(Delegate del)
		{
			System.Delegate[] delegates = this.myHandlers.GetInvocationList();
			foreach(Delegate d in delegates)
			{
				if(d == del)
					return true;
			}
			return false;
		}

		// Fire the Click event by parsing through your delegate list.
		protected override void OnClick(EventArgs e)
		{
			// First let my derived classes receive the Click event.
			foreach(Delegate d in this.myHandlers.GetInvocationList())
			{
				d.DynamicInvoke(new object[]{this, e});
			}
		}

You can then find our if a delegate is subscribed as follows:


// myControl is an instance of the above derived class.
bool subscribed = this.myControl.IsSubscribed(new EventHandler(this.myControl_Clicked));

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.