C# userControl中的HandleDestroyed事件
我有一个非常简单的自定义用户控件,名为MyControl 在我的表单中,我有以下代码(我尝试在initializeComponent之后将其放入LoadEvent和costructor中):C# userControl中的HandleDestroyed事件,c#,winforms,C#,Winforms,我有一个非常简单的自定义用户控件,名为MyControl 在我的表单中,我有以下代码(我尝试在initializeComponent之后将其放入LoadEvent和costructor中): 但是当我关闭表单时,永远不会调用表单处理程序。如果它在主表单上,那么我认为不会调用该事件。尝试在FormClosing事件中处理控件,以强制调用该事件: void Form1_FormClosing(object sender, FormClosingEventArgs e) { crl.Dispose
但是当我关闭表单时,永远不会调用表单处理程序。如果它在主表单上,那么我认为不会调用该事件。尝试在
FormClosing
事件中处理控件,以强制调用该事件:
void Form1_FormClosing(object sender, FormClosingEventArgs e) {
crl.Dispose();
}
另一种方法是将FormClosing
事件添加到UserControl
:
void UserControl1_Load(object sender, EventArgs e) {
this.ParentForm.FormClosing += new FormClosingEventHandler(ParentForm_FormClosing);
}
void ParentForm_FormClosing(object sender, FormClosingEventArgs e) {
OnHandleDestroyed(new EventArgs());
}
或在Lambda方法中:
void UserControl1_Load(object sender, EventArgs e) {
this.ParentForm.FormClosing += (s, evt) => { OnHandleDestroyed(new EventArgs()); };
}
如果结束窗体不是主窗体,则调用HandleDestroyed事件。如果主窗体关闭,则应用程序将中止,事件将不再触发 我通过如下方式启动应用程序进行了测试:
Form1 frmMain = new Form1();
frmMain.Show();
Application.Run();
现在关闭主窗体不再取消应用程序。以我这样做的形式:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
new Thread(() =>
{
Thread.Sleep(5000); // Give enough time to see the message boxes.
Application.Exit();
}).Start();
}
现在,HandleDestroyed和Disposed事件在控件上被调用
public Form1()
{
InitializeComponent();
button4.HandleDestroyed += new EventHandler(button4_HandleDestroyed);
button4.Disposed += new EventHandler(button4_Disposed);
}
void button4_Disposed(object sender, EventArgs e)
{
MessageBox.Show("Disposed");
}
void button4_HandleDestroyed(object sender, EventArgs e)
{
MessageBox.Show("HandleDestroyed");
}
哇!这解决了我的问题,现在我明白我应该显式地处理childs,而不是调用base.dispose()。。谢谢!可能重复的
public Form1()
{
InitializeComponent();
button4.HandleDestroyed += new EventHandler(button4_HandleDestroyed);
button4.Disposed += new EventHandler(button4_Disposed);
}
void button4_Disposed(object sender, EventArgs e)
{
MessageBox.Show("Disposed");
}
void button4_HandleDestroyed(object sender, EventArgs e)
{
MessageBox.Show("HandleDestroyed");
}