I have an event handler subscribed to the FormClosing event. This event handler provides dialog for the user when they exit my application; like so:
private void frmUavController_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
Dia开发者_如何学JAVAlogResult dlgResult = MessageBox.Show("Are you sure you want to exit?", "Exit?",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dlgResult == DialogResult.Yes)
{
UtilSTKScenario.PauseScenarioAnimation(UtilSTKScenario._stkObjectRoot);
}
else if (dlgResult == DialogResult.No)
{
e.Cancel = true;
}
}
Because the application runs in a side-by-side fashion; injecting COM commands into another application - I want my application to exit if the application receiving COM commands is not launched (or closed during execution). This is achieved like so:
static UtilSTKScenario()
{
// give time for active form to show
Thread.Sleep(100);
_stkProgramId = ConfigurationManager.AppSettings.Get("stkProgramId");
if (CheckIfStkIsLaunched())
{
InitAllFields();
}
else
{
HideController dHideController = new HideController(((frmUavController)Form.ActiveForm).HideControllerUi);
((frmUavController)Form.ActiveForm).Invoke(dHideController);
Application.Exit();
}
}
Calling 'Application.Exit()' causes the FormClosing event to fire. This I do not want - rather, I want the application to just exit.
Any ideas ?
WulfgarPro
You might be able to look at the event args of the FormClosing event. FormClosingEventArgs
has a CloseReason
property that may give an indicator if the form was closed by a user directly as opposed to some other mechanism.
Though I'm not clear how Application.Exit()
calls will appear... If it is also showing as CloseReason.UserClosing
then you may need to add an overload to your form [e.g. SystemClose()] to close your form and use an instance variable to tell it not to prompt within your handler.
Your FormClosing event gets a FormClosingEventArgs parameter, which has a CloseReason property. If that's CloseReason.ApplicationExitCall, then the form is closing because of a call to Application.Exit. You can just skip your "close?" prompt in that case.
private void frmUavController_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.ApplicationExitCall)
return;
// ...
The typical way to handle this sort of thing (bypass normal "do you want to close?" checks) is to use a Boolean variable. Name it something like _forceExit
, set it to true if the external event forces you to close, and if it's true, skip the dialog box in your Closing event.
Can you look at the sender object? My guess is that the sender object is different depending on you actually close the form or call the Application.Exit()
method.
精彩评论