tags:

views:

68

answers:

4

Hello guys, 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 ...
    }
}
+3  A: 

Change the miExit_Click event handler to do nothing but call Close and then let the FormClosing handler handle it either way it's being closed.

ho1
A: 

Apply DRY here. You have redundant code for Form Close.

http://en.wikipedia.org/wiki/Don't_repeat_yourself

this. __curious_geek
thanks for a link :)
alex
+3  A: 

Change the miExit_Click handlier to just call Application.Exit()

Application.Exit() automatically calls the FormClosing event on all open forms. And yes, these forms can cancel the Exit by setting their FormClosingEventArgs's Cancel property to true.

P.S. If you don't believe me, I linked to the documentation for Application.Exit(), the FormClosing bit is the first bullet point under Remarks.

R. Bemrose
A: 

Replace the contents of miExit_Click with 'this.Close();' which will in turn call MainForm_FormClosing so you don't need that code twice. Job done

w69rdy