userControl中的HandleDestroyed事件

我有一个非常简单的自定义UserControl,名为MyControl

在我的表单中,我有这个代码(我尝试将它放入LoadEvent和costructor,在InitalizeCompoment之后):

var crl = new MyControl(); Controls.Add(ctrl); ctrl.HandleDestroyed+=(sender,evt) => { MessageBox.Show("Destroyed") }; 

但是,当我关闭表单处理程序时,从未调用过。

如果它在主窗体上,那么我认为事件不会被调用。 尝试在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(); 

现在关闭主窗体不再取消应用程序。 在我这样做的forms:

 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"); }