I am working on a C#-based utility that makes use of the FormClosing event, and the event is supposed to do different things depending on whether the form was closed programatically through the form.Close(); method, or by anything else (user clicking the X, program exiting, etc.)
The FormClosingEventArgs in the FormClosing event have a property called CloseReason (of enum type CloseReason).
CloseReason could be: None, WindowShutDown, MdiFormClosing, UserClosing, TaskManagerClosing, FormOwnerClosing, ApplicationExitCall.
Ideally, there would be a way to distinguish between when the user clicks the red X, and when the Close(); method is called (through the clicking of a Continue button after other actions are performed). However, the CloseReason property in FormClosingEventArgs is set to UserClosing in both cases, so there is no way to distinguish between when the user closes the form intentially, and when the form is programmatically closed. This goes contrary to my expectation that CloseReason would equal None if the Close() method is invoked arbitrarily.
//GuideSlideReturning is an cancelable event that gets fired whenever the current "slide"-form does something to finish, be it the user clicking the Continue button or the user clicking the red X to close the window. GuideSlideReturningEventArgs contains a Result field of type GuideSlideResult, that indicates what finalizing action was performed (e.g. continue, window-close)
private void continueButton_Click(object sender, EventArgs e)
{ //handles click of Continue button
GuideSlideReturningEventArgs eventArgs = new GuideSlideReturningEventArgs(GuideSlideResult.Continue);
GuideSlideReturning(this, eventArgs);
if (!eventArgs.Cancel)
this.Close();
}
private void SingleFileSelectForm_FormClosing(object sender, FormClosingEventArgs e)
{ //handles FormClosing event
if (e.CloseReason == CloseReason.None)
return;
GuideSlideReturningEventArgs eventArgs = new GuideSlideReturningEventArgs(GuideSlideResult.Cancel);
GuideSlideReturning(this, eventArgs);
e.Cancel = eventArgs.Cancel;
}
The issue with this is that when the Close(); method is invoked after the event GuideSlideReturning finishes without being canceled, the FormClosing event handler is unable to tell that the form was closed through the method instead of being closed by the user.
What would be ideal is if I could define what the FormClosing event’s FormClosingEventArgs CloseReason would be, like this:
this.Close(CloseReason.None);
Is there a way to do this? The form.Close(); method does not have any overloads that accept any parameters, so is there a variable I can set or an alternate method I can call?
Set a flag before calling close programmatically. This can be wrapped up in a private method: