如何判断表单是通过点击 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
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 ↑