Search code examples
c#event-handlingactionbuttonclick

C# A ButtonClick action to replace all others?


I was wondering how I could set an EventHandler for a button click so that it would replace all other handlers for this objets. Ideally it would be something of the likes of:

button1.Click = MessageBox.Show("Run just this!"); //Yes, the '=' instead of the '+='.

This is because button1 already has a few click events, and I want to, in the determinated situation, overwrite all the other ones.

More examples:

button1.Click += MessageBox.Show("Event #1 has been triggered!");
button1.Click += MessageBox.Show("Event #2 and #1 have been triggered!");
button1.Click = MessageBox.Show("Event #3, and only #3, has been triggered!");

Solution

  • you can try this...

    there is a solution on the MSDN forums. The sample code below will remove all Click events from button1.

    you can keep one event on button .....

    public partial class Form1 : Form
    {
            public Form1()
            {
                InitializeComponent();
    
                button1.Click += button1_Click;
                button1.Click += button1_Click2;
                button2.Click += button2_Click;
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                MessageBox.Show("Hello");
            }
    
            private void button1_Click2(object sender, EventArgs e)
            {
                MessageBox.Show("World");
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                RemoveClickEvent(button1);
            }
    
            private void RemoveClickEvent(Button b)
            {
                FieldInfo f1 = typeof(Control).GetField("EventClick", 
                    BindingFlags.Static | BindingFlags.NonPublic);
                object obj = f1.GetValue(b);
                PropertyInfo pi = b.GetType().GetProperty("Events",  
                    BindingFlags.NonPublic | BindingFlags.Instance);
                EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
                list.RemoveHandler(obj, list[obj]);
            }
        }
    }