利用反射查找绑定事件

1.手动创建一个控件

2.反射查找事件,绑定事件到控件 

 1 private EventHandler BindEvent(ToolStripMenuItem Toostrip,string EventName)
 2 {
 3     PropertyInfo propertyInfo = (typeof(ToolStripMenuItem)).GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreReturn | BindingFlags.IgnoreCase);
 4             
 5     EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(Toostrip, null);
 6 
 7     FieldInfo fieldInfo = (typeof(ToolStripMenuItem)).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
 8          
 9     Delegate d = eventHandlerList[fieldInfo.GetValue(null)];
10     if (d != null)
11     {
12         foreach (Delegate de in d.GetInvocationList())
13         { 
14                     
15             //textBox1.Text += de.Method.Name;
16             if (d.Method.Name == EventName)
17             {
18                 return (EventHandler)d;
19             }
20         }
21     }
22     return null;
23 }

 

posted @ 2012-08-13 00:36  泽刚  阅读(305)  评论(0编辑  收藏  举报