c# - 从 "Application"向每个表单注册加载事件

标签 c# winforms

Load 事件,我可以做类似的事情

 (new Form1()).Load += 

但是,我可以从 Application Domain 向我的项目中的每个表单注册一个事件吗?是否有类似“OnFormOpen”的事件?

最佳答案

要将事件注册到项目中的每个表单,您需要创建表单的实例。然后,您需要为每个表单实例的 Load 事件分配一个委托(delegate)。

将 Load 事件分配给类型本身是不可能的,需要该类型的实例才能将处理程序分配给 Load 事件。每次创建表单实例时,可以在构造函数中包含一部分代码以注册加载事件。

这是包含 3 个表单类(Form1(启动表单)、Form2、Form3)的项目的代码片段。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        LoadEventRegister loadEventRegister = new LoadEventRegister();
        Form[] formInstances = new Form[] {new Form2(), new Form3()};
        loadEventRegister.RegisterLoadOnForms(formInstances);

        foreach (Form formInstance in formInstances)
        {
            formInstance.Show();
        }
    }
}

public class LoadEventRegister
{
    public void RegisterLoadOnForms(IEnumerable<Form> formInstances)
    {
        foreach (Form formInstance in formInstances)
        {
            EventInfo eventInfo = formInstance.GetType().GetEvent("Load");
            Type eventHandlerType = eventInfo.EventHandlerType;

            MethodInfo eventHandler = this.GetType().GetMethod("Generic_Load");

            Delegate d = Delegate.CreateDelegate(eventHandlerType, this, eventHandler);
            eventInfo.AddEventHandler(formInstance, d);
        }
    }

    public void Generic_Load(object sender, EventArgs e)
    {
        MyCustomLoad();
    }

    private void MyCustomLoad()
    {
        // Do something
    }
}

关于c# - 从 "Application"向每个表单注册加载事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4352283/

相关文章:

c# - 获取 ComboBox 的先前值

c# - 使用 OnAsyncPostBackError 比 Page_Error 有什么优势

c# - 如何将方法限制为特定线程?

c# - 为什么我从 C# 发送的 DATETIME 值存储在 SQL Server 中,相差一天/小时?

c# - 在 Windows 窗体应用程序中控制继承以获得一致的外观

c# - 自动调整 SplitContainer 面板的大小

c# - 如何检测用户是否单击了文本框的离开事件中的 X 按钮

c# - 将 AutoMapper 扩展方法从 v3 更新到 v5

c# - 我可以合并这两个 if 语句吗?

c# - 用于列标题的 ListView ContextMenuStrip