[WinForm]移除控件某个事件

关键代码:

        /// <summary>

        /// 移除控件某个事件

        /// </summary>

        /// <param name="control">控件</param>

        /// <param name="eventName">需要移除的控件名称eg:EventClick</param>

        public static void RemoveControlEvent(this Control control, string eventName)

        {

            FieldInfo _fl = typeof(Control).GetField(eventName, BindingFlags.Static | BindingFlags.NonPublic);

            if (_fl != null)

            {

                object _obj = _fl.GetValue(control);

                PropertyInfo _pi = control.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);

                EventHandlerList _eventlist = (EventHandlerList)_pi.GetValue(control, null);

                if (_obj != null && _eventlist != null)

                    _eventlist.RemoveHandler(_obj, _eventlist[_obj]);

            }

        }

使用代码:

        private void WinRemoveControlEventTest_Load(object sender, EventArgs e)

        {

            button1.RemoveControlEvent("EventClick");

        }

        private void button1_Click(object sender, EventArgs e)

        {

            MessageBox.Show("button1_Click");

        }

你可能感兴趣的:(WinForm)