1

I am trying to reset my main form so that I can reset all text boxes and variables easily. I have added a bool to my Progam.cs to enable the application to stay open while the form is closed and then re-opened. When I try to close it, the on_closing even fires twice. I'm not sure what to do to stop it happening, but I know it's got to be something simple.

Program.cs:

static class Program
{
    public static bool KeepRunning { get; set; }
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        KeepRunning = true;
        while (KeepRunning)
        {
            KeepRunning = false;
            Application.Run(new Form1());
        }

    }
}

Form1:

private void button1_Click(object sender, EventArgs e)
    {
        Program.KeepRunning = true;
        this.Close();
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("You have unsaved work! Save before closing?", "Save?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
        if (dialogResult == DialogResult.Yes)
        {
            e.Cancel = true;
            MessageBox.Show("saving then closing");
            Application.Exit();
        }

        if (dialogResult == DialogResult.No)
        {
            MessageBox.Show("closing");
            Application.Exit();
        }

        if (dialogResult == DialogResult.Cancel)
        {
            e.Cancel = true;
            MessageBox.Show("canceling");
        }
    }
svick
  • 236,525
  • 50
  • 385
  • 514
Rikki B
  • 636
  • 8
  • 23
  • @HansPassant, I'd say this is certainly not a duplicate and quite likely to be another duplicate syndrome case. Even if the solution would be the same, these are different questions. – Fabio Milheiro Mar 24 '13 at 01:48
  • "Closing a form without closing the application", exact same question. – Hans Passant Mar 24 '13 at 01:51

2 Answers2

0

Remove your Application.Exit(). Since you are already in the FormClosing Event Handler, the Application will exit if Program.KeepRunning is set to false.

darthmaim
  • 4,970
  • 1
  • 27
  • 40
0

This happens because you call Application.Exit(). Since, your form is not closed yet, if you try to close the application, that instruction will try to close the form fist which, in turn, will call the event handler a second time.

Also, I don't think you need Application.Exit() because that's your only form and the application will, therefore, close automatically (at least that's what happened in my VB6 old times!)

Fabio Milheiro
  • 8,100
  • 17
  • 57
  • 96