Answered by:
Ameding the outcome of clicking the exit (cross in box) button in a Windows Form

Question
-
Hi,
I'm trying to change it so that, is the user clicks on the "cross in a box" button to close the program, they get asked if they are sure, and writes some details to a log file.
When I use the code below, if I click YES, I get asked the same question again. if I click yes again, then the line gets written, and the program closes.
If I click No, the program closes (it shouldn't, it should close the messagebox and leave the program open).
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("Are you sure you want to close the interface?", "Leave program? ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { System.IO.File.AppendAllText(errorlogpath, extmsg); Application.Exit(); } else { return; } }
Now, I'm sure its something I am doing wrong (as this is the first time I have tried to amened this function), but if someone can help me with WHAT I have done wrong, that would be great :-)
Thanks
Tuesday, February 20, 2018 11:44 AM
Answers
-
Don't call
Application.Exit();
just
e.Cancel = false;
- Marked as answer by G-Oker Tuesday, February 20, 2018 12:55 PM
Tuesday, February 20, 2018 12:52 PM
All replies
-
See the sample from Form.Closing EventTuesday, February 20, 2018 11:56 AM
-
Hi Castorix31,
thank you for pointing me to that.
That has now "fixed" the No button problem, but I still get the message box twice if I click yes (even if I put e.Cancel = false in.
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("Are you sure you want to close the interface?", "Leave program? ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { System.IO.File.AppendAllText(errorlogpath, extmsg); Application.Exit(); } else { e.Cancel = true; } }
thanks
Tuesday, February 20, 2018 12:06 PM -
Don't call
Application.Exit();
just
e.Cancel = false;
- Marked as answer by G-Oker Tuesday, February 20, 2018 12:55 PM
Tuesday, February 20, 2018 12:52 PM -
EXCELLENT. Thank youTuesday, February 20, 2018 12:55 PM