直接上代碼了
可以直接用
/// <summary>
/// 查找控件的對應的事件註冊的方法名
/// </summary>
/// <param name="control">控件</param>
/// <param name="eventName">事件</param>
/// <returns>返回事件註冊的方法名,若未找到則返回null</returns>
private static string GetBindingMethod(Control control, string eventName)
{
//EventInfo info = control.GetType().GetEvent(eventName);
PropertyInfo propertyInfo = control.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
if (propertyInfo == null) { return null; }
EventHandlerList eventList = (EventHandlerList)propertyInfo.GetValue(control, null);
FieldInfo fieldInfo = typeof(Control).GetField("Event" + eventName, BindingFlags.Static | BindingFlags.NonPublic);
if (fieldInfo == null) { return null; }
Delegate delegateInfo = eventList[fieldInfo.GetValue(control)];
if (delegateInfo == null) { return null; }
Delegate[] delegateList = delegateInfo.GetInvocationList();
return delegateList[delegateList.Length - 1].Method.Name;
}
如果想判斷對應的控件有沒有對應的事件;
可以稍微改變一下代碼,遍歷delegateList 即可;