我想为我项目中的所有表单添加额外的事件处理程序。当每个表单Load event
被触发时,除了 Form_Load() 中编写的代码之外,我的事件处理程序也将被执行。
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
namespace eventHandlerIntercept {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//intercept all form's Load event
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly a in assemblies)
{
Type[] types = a.GetTypes();
foreach (Type t in types)
{
if (t.IsPublic && t.BaseType == typeof(Form))
{
if (t.Namespace.Contains("eventHandlerIntercept"))
{
EventInfo e1 = t.GetEvent("Load");
MethodInfo mi = typeof(Program).GetMethod("HandleCustomEvent");
Delegate handler = Delegate.CreateDelegate(e1.EventHandlerType, mi);
object o1 = Activator.CreateInstance(t);
e1.AddEventHandler(o1, handler);
}
}
}
}
Application.Run(new Form1());
}
public static void HandleCustomEvent(object sender, EventArgs a)
{
// Do something useful here.
MessageBox.Show("xyz");
}
}
}
这段代码编译没有错误,但是当Form1显示时,它没有显示message box
内容是xyz
什么,我的代码哪里有问题?