Really closing my application [CS/C# 2005]

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
This is a really annoying and yet probably trival issue but ...
I have a main form (frmMainMenu) where the users have a couple of choices of other forms to view, when they do that frmMainMenu is hidden (as it is no longer required but it is the starting point of everthing so can't just get rid of it).

Anyways - so frmMainMenu is hidden (this.Hide()) and it creates and .Shows other forms, these in turn may also lead to other forms (where they will then be hidden) and so on...

Now to the problem - funny thing is when all is said and done and I EXIT (hit the 'x' in the top-right corner of the window) I expect my application (all of it) to close but instead it remains in memory (I have to kill it manually via the process list)...
I assume this is because when I click the 'x' it only closes THAT form and all the hidden ones that came before it are still running but are just "hidden"...

Well when I hit the 'x' on ANY of my forms I want the entire application to close (gracefully, no leaks due to forms, etc...) as it should...
Any ideas, hints, and help would be greatly appreciated, thanks
 
You will have to maintain a static list of open forms so that they can be closed from the closing event of the current form. Application.Exit() will also do the job, but isn't the best idea because it just 'yanks the sheet from under' your application rather that closing tidily.
 
Close the form which your application uses to start the message loop, and it will end because the message loop will be terminated. That is the only one you need to explicitly close.
 
mutant: isn't that essentially what Application.Exit(); does? I was going to put it in the "FormClosing" event of EACH form - I was reading that Application.Exit() will return from the Application.Run(MainForm); in the Main Menu - isn't that a safe way to do it?

Cags: What about:
Code:
            for (int i = 0; i <= Application.OpenForms.Count-1; i++)
            {
                if (Application.OpenForms[i] != this)
                    Application.OpenForms[i].Close();
            }
            Application.Exit();

What do you thinkz
 
Last edited:
I think that Application.Exit is generally looked down upon. Resorting to it is generally a sign that you need to re-evaluate your design. Mutant is right, closing the main form is usually the way that an application is closed.

Perhaps the main form should handle the Closing event of each other form and determine for itself when it should be closed. Or perhaps when a form is closed it should notify the main form. Application.Exit will probably suffice, but if the program were to become larger and more complex or you write another application that is larger and more complex it can become a problem that exactly which class is controlling the application in what manner is unclear.
 
Back
Top