I am trying to close my winforms application through the Form.Closing event, with a custom message (Do you want to exit yes/no). For this I have edited the onFormClosing event for every form in my c# project. Like so:
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
// Confirm user wants to close
switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing", MessageBoxButtons.YesNo))
{
case DialogResult.No:
e.Cancel = true;
break;
default:
break;
}
}
When the user clicks Yes, I want to get the entire application to exit. However, I have a main form which functions as a loginform. When the user logs in, the mainform gets hidden and a different form displays.
So when the user clicks Yes, the entire application does not end, because of that hidden form. How can I make sure that the entire application gets shut down?
I have tried Application.Exit(), this fires the messagebox confirming the shutdown again, because it calls the OnFormClosing event.
You can explicitly handle Application.Exit
as its own reason:
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown
|| e.CloseReason == CloseReason.ApplicationExitCall)
return;
This would let you use Application.Exit()
to shut down correctly in the handler. Alternatively, you could just close the main (hidden) form directly.
Reeds solution is the best, if you want you could also try this:
System.Diagnostics.Process.GetCurrentProcess().Kill();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With