【问题标题】:How do I prevent a form object from disposing on close?如何防止表单对象在关闭时处理?
【发布时间】:2011-08-28 23:06:50
【问题描述】:

我正在使用 MDIParent 表单。当我关闭它的孩子时,孩子的对象就会被处置。有没有办法将子可见性设置为 false 而不是处置?

【问题讨论】:

  • 覆盖处理这个的关闭事件。当然,如果这样做了,那么您将拥有无法看到的内容。
  • 这里的所有答案都缺少魔法酱。如果您只处理FormClosing 事件而没有特殊情况,您将永远无法关闭应用程序。哎呀!这可能不是您或用户想要的。不过,我对上述重复问题的回答中的代码是正确的,并且在这两种情况下都可以顺利运行。

标签: c# winforms dispose formclosing


【解决方案1】:

默认情况下,当您关闭表单时,它会被释放。您必须覆盖 Closing 事件以防止它发生,例如:

// Use this event handler for the FormClosing event.
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
  this.Hide();
  e.Cancel = true; // this cancels the close event.
}

【讨论】:

  • 仅当表单使用 Show 方法显示时才适用。如果表单用 ShowDialog 显示,则不会自动释放。
  • 我已经将它应用到我的表单中,但是视觉组件 Dispose 函数无论如何都会被调用。它只是帮助,而不是关闭表单。
  • 还有一点要知道,你可以检查e.CloseReason来确定用户或应用程序是否调用了FormClose方法。
【解决方案2】:

您可以取消关闭事件并改为隐藏。

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
        this.Hide();
    }

【讨论】:

  • 与接受的答案相比,这是相反的调用顺序。顺序重要吗?
  • 不,顺序无关紧要。
【解决方案3】:

是的。您可以调用表单的“隐藏”方法。

你也可以重写 OnClosed 而不调用它的基本实现;但是,当您确实想要处理表单时,这可能会妨碍您。

【讨论】:

  • 我不这么认为。当您覆盖 Closed 事件时,为时已晚:)
【解决方案4】:

当然,您可以取消关闭并隐藏它。这似乎不是一件好事,但你绝对可以。

请参阅 Form.FormClosing Event (MSDN)。

【讨论】:

    【解决方案5】:
        void SaveInfo()
    {
    blnCanCloseForm = false;
    Vosol[] vs = getAdd2DBVosol();
    if (DGError.RowCount > 0)
    return;
    
    Thread myThread = new Thread(() =>
    {
    this.Invoke((MethodInvoker)delegate {
        picLoad.Visible = true;
        lblProcces.Text = "Saving ...";
    });
    int intError = setAdd2DBVsosol(vs);
    Action action = (() =>
    {
        if (intError > 0)
        {
            objVosolError = objVosolError.Where(c => c != null).ToArray();
            DGError.DataSource = objVosolError;// dtErrorDup.DefaultView;
            DGError.Refresh();
            DGError.Show();
            lblMSG.Text = "Check Errors...";
        }
        else
        {
            MessageBox.Show("Saved All Records...");
            blnCanCloseForm = true;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    
    });
    this.Invoke((MethodInvoker)delegate {
        picLoad.Visible = false;
        lblProcces.Text = "";
    });
    this.BeginInvoke(action);
    });
    myThread.Start();
    }
    
    void frmExcellImportInfo_FormClosing(object s, FormClosingEventArgs e)
    {
        if (!blnCanCloseForm)
            e.Cancel = true;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-19
      • 1970-01-01
      • 2018-02-20
      • 1970-01-01
      • 2021-12-07
      • 2022-01-06
      相关资源
      最近更新 更多