How would it be possible to remove all event handlers of the 'Click' event of a 'Button'?

后端 未结 6 622
孤街浪徒
孤街浪徒 2020-11-28 11:56

I have a button control, and I\'d need to remove all the event handlers attached to its Click event.

How would that be possible?

Button button = GetB         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 12:29

    I was working on WinForms project where I had to remove the click-EventHandler from a ToolStripMenuItem and replace it with my own Handler. (I had to modify the action taken when a contextMenu Item was clicked)

    for me the code from user2113340 did not work. I had to modify it like this to work with ToolStripMenuItem:

        private void RemoveClickEvent(ToolStripMenuItem control)
        {
            FieldInfo eventClick = typeof(Control).GetField("EventClick", BindingFlags.NonPublic | BindingFlags.Static);
            PropertyInfo eventsProp = typeof(Component).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
            EventHandlerList events = (EventHandlerList)eventsProp.GetValue(control, null);
            FieldInfo headInfo = events.GetType().GetField("head", BindingFlags.NonPublic | BindingFlags.Instance);
            object head = headInfo.GetValue(events);
            FieldInfo keyType = head.GetType().GetField("key", BindingFlags.NonPublic | BindingFlags.Instance);
            object key = keyType.GetValue(head);
            Delegate d1 = events[key];
            events.RemoveHandler(key, d1);
        }
    

提交回复
热议问题