I've a parent form with a child form, called by its parent by clicking on a button.
private void button3_Click(object sender, EventArgs e)
{
if (Application.OpenForms.OfType<Form2>().Count() < 1 )
{
Form2 form2 = new Form2();
form2.Show(this);
}
}
On both forms (the parent and the child) I've a messagebox to confirm the closing of the current form.
void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Do you want to exit?",
"Close application",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information) == DialogResult.No)
{
e.Cancel = true;
}
}
and
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
//MessageBox.Show("You pressed: " + sender);
if (MessageBox.Show("Do you want to close the child form?",
"Child form closing",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information) == DialogResult.No)
{
e.Cancel = true;
}
}
They work good but when I try to close the program, by closing the parent form having the child opened, the closing event on the parent form triggers also the messagebox on the child, so I've to click "Yes i want to close" double: one time on the child one and another on the parent..
How can I manage this situations, so exit the program having one child form opened by closing the parent form?
I found the solution by adding the close reason in each FormClosing event:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
if (MessageBox.Show("Do you want to exit?",
"Closing application",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information) == DialogResult.No)
{
e.Cancel = true;
}
}
}
Hope this could help anyone.