Reputation: 31
I want to add additional eventhandler to all forms in my project.
when each form Load event
is fired,beside the code written in Form_Load(),
my eventhandler will also be executed.
this is my code :
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");
}
}
}
this code compile with no error ,but when Form1 display,it does not show a message box
which content is xyz
,where is the problem with my code?
Upvotes: 0
Views: 477
Reputation: 3005
You can try this:
Form myForm = new Form();
myForm.Load += HandleCustomEvent;
Application.Run(myForm);
That worked for me, but the MessageBox
is showed before the form itself, I don't know if that matters to you. Still, hope this helps, please feedback.
Upvotes: 1
Reputation: 100547
There is no way to "intercept all form's Load event" by trying to do something with types. OnLoad event is instance event, so there is no way to add handler before instance of Form
-derived object is created.
Your code actually creates instances of all From-derived classes and add listener, but you completely ignore resulting object and create one new for call to Run
. To make that approach working you need to pass o1
corresponding to Form1
type to Run
method.
You may want to write some sort of factory method that would create forms by type name and immediately attach your handler. And than you can use this method wherever you need to create new form (instead of calling constructor directly).
Upvotes: 1