C# close all forms
c#, forms
Solution
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
}
}
Problem
I have a problem with my program. I have 3 Forms: First one opens a second form. Second one opens a third form or returns to the first form. The third form can open the first or second forms. This is how I open a second Form: ``` private void Open_second_form() { Form2 myForm = new Form2(Type_person); this.Hide(); myForm.ShowDialog(); this.Close(); } ``` The rest of the forms I open exactly the same. Here is a code for how I close forms. Every Form has this method: ``` private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("Exit or no?", "My First Application", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No) { this.Close(); Environment.Exit(1); } } ``` When I open the third form I get 3 MessagesBoxes. If I open first form I got only 1 MessageBox. I want to close all forms while getting only one MessageBox. I tried a lot of solutions but none worked. I tried `Application.exit();` Please help me :)