WinForms FAQ - Events

Find answers for the most frequently asked questions
Expand All Collapse All

In C# you could intercept what gets subscribed as follows:


// In a Control derived class, for example: // Use override if the base class property was marked as virtual 
public new event EventHandler Click
{
    add
    {
        // Do not let derived classes subscribe to this event, they should instead override OnClick. 
        if (value.Target != this) base.Click += value;
    }
    remove { base.Click -= value; }
}
Permalink

In C#, you can do as follows:


		// Use a custom Delegate to hold your subscribers
		private EventHandler myHandlers;
		// Control Click event firing, for example.
		public new event EventHandler Click
		{
			add
			{
				this.myHandlers += value;
			}
			remove
			{
				this.myHandlers -= value;
			}
		}

		protected override void OnClick(EventArgs e)
		{
			// First let my derived classes receive the Click event.
			foreach(Delegate d in this.myHandler.GetInvocationList())
			{
				if(d.Target == this)
				{
					d.DynamicInvoke(new object[]{this, e});
					break;
				}
			}
			// Then let other subscribers receive the Click event.
			foreach(Delegate d in this.myHandler.GetInvocationList())
			{
				if(d.Target != this)
					d.DynamicInvoke(new object[]{this, e});
			}

		}
Permalink

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));
Permalink

Share with

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

Please submit your question and answer.