Reputation: 201
How can I find out if a form is closed by clicking the X button or by (this.Close())?
Upvotes: 8
Views: 20542
Reputation: 4589
the form has the event FormClosing with parameter of type 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;
}
}
}
Upvotes: 24
Reputation: 181
For the OnFormClosing
the FormClosingEventArgs.CloseReason
is UserClosing
either to 'X' button or form.Close()
method.
My solution:
//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 ↑
In this example the close (X) button does not close the form
Upvotes: 0
Reputation: 11
If you want to set the returned field to null, like you do when you click Cancel in your Form:
private void Form1_FormClosing( object sender, FormClosingEventArgs e )
{
if ( e.CloseReason == CloseReason.UserClosing )
{
returnfield = null;
this.close();
}
}
Upvotes: 1
Reputation: 1133
You could remove the 'X' altogether?
One of the properties of the form is "ControlBox" just set this to false
Upvotes: 3