How do I prevent a form object from disposing on close?

烈酒焚心 提交于 2019-11-29 05:40:40

By default, when you close a form, it will be disposed. You have to override the Closing event to prevent it, for example:

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

You can cancel the close event and hide instead.

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

Yes. You can call the form's "Hide" method.

You can also override OnClosed and not call its base implementation; HOWEVER, when you DO want to dispose of the form, this may get in your way.

Fosco

Sure, you can cancel the close and hide it. It doesn't seem like a good thing to do, but you definitely can.

See Form.FormClosing Event (MSDN).

    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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!