【问题标题】:HandleDestroyed event in userControluserControl 中的 HandleDestroyed 事件
【发布时间】:2011-12-28 15:36:50
【问题描述】:

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

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

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

但是当我关闭表单处理程序时,它永远不会被调用。

【问题讨论】:

标签: c# winforms


【解决方案1】:

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

【讨论】:

  • 哇.. 它解决了我的问题,现在我明白我应该明确处置孩子,而不是通过调用 base.dispose().. 非常感谢!
【解决方案2】:

如果关闭窗体不是主窗体,则会调用 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");
}

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多