C# · 12月 26, 2021

WinForm实现移除控件某个事件的方法

本文实例讲述了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){ Message@R_375_2419@.Show(“button1_Click”);}