C# close all forms
Your confirmation message is funny and result is unobvious =D
There are 2 solutions possible to your issue.
1) If user chooses to close application - don't display confirmation anymore
private static bool _exiting;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!_exiting && MessageBox.Show("Are you sure want to exit?",
"My First Application",
MessageBoxButtons.OkCancel,
MessageBoxIcon.Information) == DialogResult.Ok)
{
_exiting = true;
// this.Close(); // you don't need that, it's already closing
Environment.Exit(1);
}
}
2) use CloseReason
to confirm only user actions
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
if(MessageBox.Show("Are you sure want to exit?",
"My First Application",
MessageBoxButtons.OkCancel,
MessageBoxIcon.Information) == DialogResult.Ok)
Environment.Exit(1);
else
e.Cancel = true; // to don't close form is user change his mind
}
}
Call the Environment.Exit(0); method
private void btnExit_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
I'm using this snippet always on my menu form. I hope this helps.
for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
{
if (Application.OpenForms[i].Name != "Menu")
Application.OpenForms[i].Close();
}