如何防止表单对象在关闭时被丢弃?

问题描述 投票:0回答:5

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

c# winforms dispose formclosing
5个回答
48
投票

默认情况下,当您关闭表单时,它将被丢弃。您必须重写

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.
}

记得添加方法,例如在形式 ctor 中:

public MyForm()
{
    InitializeComponent();

    this.FormClosing += MyForm_FormClosing;
}

4
投票

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

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

2
投票

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

您还可以重写 OnClosed 并且不调用其基本实现;但是,当您确实想要处理该表格时,这可能会妨碍您。


0
投票

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

请参阅 Form.FormClosing 事件 (MSDN)。


0
投票
    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;
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.