【发布时间】:2010-09-17 13:40:45
【问题描述】:
如何查看表单是否通过单击 X 按钮或 (this.Close()) 关闭?
【问题讨论】:
-
这个比给它写代码更简单。
如何查看表单是否通过单击 X 按钮或 (this.Close()) 关闭?
【问题讨论】:
表单有事件FormClosing,参数类型为FormClosingEventArgs。
// catch the form closing event
private void Form1_FormClosing( object sender, FormClosingEventArgs e )
{
// check the reason (UserClosing)
if ( e.CloseReason == CloseReason.UserClosing )
{
// do stuff like asking user
if ( MessageBox.Show( this,
"Are you sure you want to close the form?",
"Closing Form",
MessageBoxButtons.OKCancel,
MessageBoxIcon.Question ) == DialogResult.Cancel )
{
// cancel the form closing if necessary
e.Cancel = true;
}
}
}
【讨论】:
您可以完全删除“X”吗?
表单的属性之一是“ControlBox”,只需将其设置为false
【讨论】:
如果您想将返回的字段设置为 null,就像您在表单中单击“取消”时所做的那样:
private void Form1_FormClosing( object sender, FormClosingEventArgs e )
{
if ( e.CloseReason == CloseReason.UserClosing )
{
returnfield = null;
this.close();
}
}
【讨论】:
对于OnFormClosing,FormClosingEventArgs.CloseReason 是UserClosing要么是“X”按钮,要么是form.Close() 方法。
我的解决方案:
//override the OnFormClosing event
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.ApplicationExitCall)// the reason that you need
base.OnFormClosing(e);
else e.Cancel = true; // cancel if the close reason is not the expected one
}
//create a new method that allows to handle the close reasons
public void closeForm(FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing) this.Close();
else e.Cancel = true;
}
//if you want to close the form or deny the X button action invoke closeForm method
myForm.closeForm(new FormClosingEventArgs(CloseReason.ApplicationExitCall, false));
//the reason that you want ↑
在本例中,关闭 (X) 按钮不会关闭表单
【讨论】: