1 using System;
2 using System.Collections.Generic;
3 using System.Windows.Forms;
4 using System.Reflection;
5
6 namespace WindowsApplication9
7 {
8
9 interface IAction
10 {
11 void Run();
12 }
13
14 class EventHandler<T> where T : EventArgs
15 {
16 public EventHandler( IAction action )
17 {
18 this.action = action;
19 }
20
21 IAction action;
22
23 public void Handler(object sender,T e)
24 {
25 action.Run();
26 }
27 }
28
29 static class Program
30 {
31 private static MethodInfo GetDelegateMethodInfo( Delegate deleg )
32 {
33 return deleg.Method;
34 }
35
36 public static void AttachEvent(Form form, string controlName, string eventName, IAction action)
37 {
38 Control[] controls = form.Controls.Find(controlName, true);
39 if (controls != null && controls.Length > 0)
40 {
41 foreach (Control control in controls)
42 {
43 EventInfo eventInfo = control.GetType().GetEvent(eventName);
44 if (eventInfo != null)
45 {
46 Type tHandler = eventInfo.EventHandlerType;
47 MethodInfo method = tHandler.GetMethod("Invoke");
48 ParameterInfo[] param = method.GetParameters();
49 Type t = typeof(WindowsApplication9.EventHandler<EventArgs>);
50 t = t.GetGenericTypeDefinition();
51 Type tHandlerInstance = t.MakeGenericType( param[1].ParameterType );
52 object o = tHandlerInstance.GetConstructor( new Type[] { typeof(IAction) } )
53 .Invoke(new object[] { action } );
54 MethodInfo m= tHandlerInstance.GetMethod("Handler");
55
56 eventInfo.AddEventHandler(control,
57 Delegate.CreateDelegate( eventInfo.EventHandlerType,o,m )
58 );
59 }
60 }
61 }
62 }
63
64 class ActionImpl : IAction
65 {
66 public void Run()
67 {
68 System.Diagnostics.Debug.WriteLine("Action Executed");
69 }
70 }
71
72 /// <summary>
73 /// The main entry point for the application.
74 /// </summary>
75 [STAThread]
76 static void Main()
77 {
78 IAction action = new ActionImpl();
79 Application.EnableVisualStyles();
80 Application.SetCompatibleTextRenderingDefault(false);
81 Form1 f = new Form1();
82 AttachEvent( f,"textBox1","Validating",action );
83
84 Application.Run(f);
85 }
86 }
87 }