Reputation: 181
I have VS2015 Windows Form, and whenever I click X to close application, it prompts me to close it or not. When I press No, then the pop up window would close. However, when I press Yes, it pops up another same window, and asks me to close it or not.
How can I solve this issue? I want to close my form at first popup.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
const string closemsg = "Do you really want to close the program?";
const string exit = "Exit";
DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
Application.Exit();
}
else if (dialog == DialogResult.No)
{
e.Cancel = true;
}
}
Upvotes: 0
Views: 324
Reputation: 26
It is very simple. Make remove Application.Exit();
Application.Exit() generates the FormClosing event.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
const string closemsg = "Do you really want to close the program?";
const string exit = "Exit";
DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
//Remove Application.Exit();
//Application.Exit();
}
else if (dialog == DialogResult.No)
{
e.Cancel = true;
}
}
Upvotes: 1
Reputation:
However, when I press Yes, it pops up another same window, and asks me to close it or not.
The reason is because your Form1_FormClosing
will be called again. Try setting a _isExiting
flag that you can test upon entry.
Try this:
bool _isExiting;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (_isExiting)
{
// whoops, been here already, time to go!
return;
}
const string closemsg = "Do you really want to close the program?";
const string exit = "Exit";
DialogResult dialog = MessageBox.Show(closemsg, exit, MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
_isExiting=true; // set flag here so we don't repeat this exercise again
Application.Exit();
}
else if (dialog == DialogResult.No)
{
e.Cancel = true;
}
}
Upvotes: 1