I have a MainForm. I can close it by using a close button (upper right corner) or by clicking a menuitem miExit.
My problem is when I clicked miExit and answered “OK”, it shows messageBox TWICE. How can I fix it ? (I understand why it shows twice but how can I avoid it ?)
Both formclosing and miExit clicks must provide messagebox with “Exit ?” prompt.
partial class MainForm : Form
{
void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("Exit ?", "Exit", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
SaveSettings();
}
else
{
e.Cancel = true;
}
}
void miExit_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Exit ?", "Exit", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
SaveSettings();
Application.Exit();
}
}
void SaveSettings()
{
// save user settings to file ...
}
}
Change the
miExit_Clickhandlier to just callApplication.Exit()Application.Exit()automatically calls theFormClosingevent on all open forms. And yes, these forms can cancel the Exit by setting theirFormClosingEventArgs‘sCancelproperty totrue.P.S. If you don’t believe me, I linked to the documentation for
Application.Exit(), theFormClosingbit is the first bullet point under Remarks.