Reputation: 642
I'm having some issues with terminating an application process after closing the application with the application close button.
The application uses multiple forms and utilizes MDI parent/child interface.
In each form .cs
file, I have the following code (substituting FormName
with the actual form name):
private void FormName_Closing(object sender, FormClosingEventArgs e)
{
Environment.Exit(0);
}
If I close the first window that opens after the application starts, the process ends as expected. However, if I open a new form with a button (new MDI child) and click the application close button, the application closes, but the process is still active in the task manager.
I have tried using Application.Exit
in lieu of Environment.Exit(0)
but to no avail.
Is there any way to terminate the whole application process when any form is closed?
Upvotes: 2
Views: 1745
Reputation: 13871
Use Application.OpenForms
to get all the forms, and close them all.
public void CloseAllForms()
{
foreach (var form in Application.OpenForms.ToArray()) {
CloseForm(form);
}
}
One subtle issue here is that forms can be opened from different threads, in which case simply closing them from the main thread won't work - you'd need to close such forms via Invoke
:
private void CloseForm(Form form)
{
if (form.IsDisposed) {
return;
}
if (form.InvokeRequired) {
form.Invoke((MethodInvoker)form.Close);
}
else {
form.Close();
}
}
Upvotes: 1
Reputation: 437
You could try something like this to ensure all of the forms get closed.
private void FormName_Closing(object sender, FormClosingEventArgs e)
{
Form parent = this;
while (parent.MdiParent != null)
parent = parent.MdiParent;
closeChildren(parent);
parent.Close();
}
static void closeChildren(Form parent)
{
foreach (var child in parent.MdiChildren)
{
closeChildren(child);
child.Close();
}
}
If closing all of the forms does not work, then you will need to ensure that any threads you started get stopped when the application is closing as the process does not stop until all threads have ceased.
Upvotes: 0