Reputation:
Hey. When I say close, I do not speak of the method close(), but when a user hits the close button to the window. I have multiple forms, that show and hide depending on if the user is logged in or about to log in and so on. When the user finaly close one of the forms, I want them all to just exit. Now, when a user closes a form, the program is still running because there is a form in the background hiding.
How can I exit on close, I remember doing this in Java, thanks.
Upvotes: 1
Views: 33414
Reputation: 593
private void btnExit_Click(object sender, EventArgs e)
{
for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
{
if (Application.OpenForms[i].Name != "Menu")
Application.OpenForms[i].Close();
}
}
Upvotes: 6
Reputation: 11
I tried solve same problem and this is working fine:
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
Upvotes: 0
Reputation: 593
Call the Environment.Exit(0); method
private void btnExit_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
Upvotes: 2
Reputation: 2752
Only call Application.Exit() if you know, that the rest of the application can close ungracefully. If other open forms need to do something in their FormClosing event, this wont get done. Using Application.Exit() is a "bad code smell" meaning that there is something wrong with your design.
Do centralized event handling that all forms subsribe to, so they can be notified when the application is closing. There are also plenty of other ways to handle this, Teh Googles knows :)
Upvotes: 1