Reputation: 6512
I am trying to view a message box. this should happen when the user tries to exit the program while there are child windows active. if there are no active child windows then the application should end. i have written some code but when the user clicks on NO, the message box immediately pops up again.if you have a better way of doing this please feel free to share, thank you.
private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
Form child = this.ActiveMdiChild;
if(child != null)
{
DialogResult res =
MessageBox.Show( child.Name +
"Do you want to exit?", "Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (res == DialogResult.No)
{
e.Cancel = true;
child.Focus();
}
else if (res == DialogResult.Yes)
{
Application.Exit();
}
}
else if (child == null)
{
Application.Exit();
}
}
Upvotes: 3
Views: 12043
Reputation: 16761
According to MSDN if there are child form who canceled closing then main form will have its e.Cancel
already set to true. Also there's no need to call Application.Exit()
, because after the main form closes the application should end. Try this:
private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
Form child = this.ActiveMdiChild;
if (child != null)
{
DialogResult res =
MessageBox.Show( child.Name +
"Do you want to exit?", "Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (res == DialogResult.No)
{
e.Cancel = true;
child.Focus();
}
else
{
e.Cancel = false;
}
}
}
Upvotes: 4
Reputation: 1883
else if (res == DialogResult.Yes)
{
Application.Exit();
}
just remove this from your code code
Upvotes: 0
Reputation: 4624
It's because of the call to Application.Exit(). Why do you need it if it is the Main form anyway? You can filter this out by adding this check on the top of the function
if(e.CloseReason == CloseReason.ApplicationExitCall) return;
Upvotes: 0
Reputation: 3214
Perhaps you're handling the FormClosing
event multiple times. Can you paste code that adds MainWindow_FormClosing
to the event?
Upvotes: 0