2011-05-19 32 views
15

我正在使用MDIParent表单。当我关闭孩子时,孩子的对象会被处理。有没有办法将孩子的可见度设置为错误而不是处置?如何防止表单对象关闭处置?

+0

覆盖处理这一close事件。当然,如果这样做,那么你有东西的记忆,只是无法看到。 – 2011-05-19 14:48:52

+0

[在关闭C#上隐藏MDI子窗体]的可能重复项目(http://stackoverflow.com/questions/6020210/hiding-mdi-child-forms-on-close-c) – 2011-05-19 14:51:51

+3

这里的所有答案都缺少魔术酱。如果你只处理'FormClosing'事件而没有特殊情况,你将永远无法关闭应用程序。哎呦!这可能不是你或用户的意图。然而,我在上述链接重复问题的答案中的代码是正确的,并且在这两种情况下都没有问题。 – 2011-05-19 14:53:50

回答

31

默认情况下,当您关闭表单时,它将被丢弃。你必须重写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. 
} 
+9

只有在使用Show方法显示窗体时才会出现这种情况。如果窗体与ShowDialog一起显示,则不会自动处理。 – 2011-05-19 18:34:57

+1

我已经将这个应用于我的表单,但无论如何都调用了可视组件'Dispose'函数。它只有帮助,而不是关闭表格。 – Javidan 2014-03-03 08:42:10

+0

另一件需要知道的事情是,您可以检查'e.CloseReason'来确定用户或应用程序是否调用'Form'的'Close'方法。 – KDecker 2017-02-24 17:53:31

2

是的。您可以调用窗体的“隐藏”方法。

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

+2

我不这么认为。当您重写Closed事件时,已经太迟了:) – Vimvq1987 2011-05-19 14:52:26

0

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

请参阅(MSDN)。

2

可以取消close事件和隐藏来代替。

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

与接受的答案相比,这是调用的相反顺序。订单是否重要? – 2015-01-26 16:02:47

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