Csharp/C#教程:userControl中的HandleDestroyed事件分享


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事件。

上述就是C#学习教程:userControl中的HandleDestroyed事件分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/991203.html

(0)
上一篇 2021年12月23日
下一篇 2021年12月23日

精彩推荐