gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:53 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com