プロジェクトのすべてのフォームにイベント ハンドラを追加したいと考えています。各フォーム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");
}
}
}
message box
このコードはエラーなしでコンパイルされますが、Form1 が表示されると、コンテンツが表示されませんxyz
。コードの問題はどこにありますか?