Search code examples
c#formshideformclosing

Hiding a form without calling FormClosing method


I have two forms and I have linked it up so that when the second form is closed the first is closed too (using the FormClosing method).

The problem with this is that when I wish to hide the second form it automatically closes the first. Is there a way in which a form can be hidden without actually calling the FormClosing method?

The FormClosing method still seems to be called when "Visible = false" and "Hide()" are used.

Thanks.


Solution

  • I changed my program so that it is started as below:

            MainForm mainForm = new MainForm();
            mainForm.Show();
            Application.Run();
    

    Instead of:

            Application.Run(new MainForm());
    

    In each of the forms I have added a FormClosing event which checks to see if the user has opted to close the application. If this is the case a prompt is shown to the user to ask for their confirmation:

        private void ImageSelect_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                if (DialogResult.No == MessageBox.Show("Are you sure you wish to exit?", "Exit Confirmation", MessageBoxButtons.YesNo))
                    e.Cancel = true;
                else { Application.Exit(); }
            }
        }
    

    The application now can be closed from any form in the application.