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 :)
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();
}
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