C#窗体关闭技术咨询:批量关闭多窗体及子窗体联动主窗体
Hey fellow C# dev! Let's work through those two WinForms closing problems you're dealing with—these are super common, so I've got straightforward solutions for you.
If you need to shut down all open child forms while keeping your main form running, you'll want to loop through the Application.OpenForms collection. But here's a gotcha: you can't iterate directly over this collection because closing a form modifies it, which will throw an exception. Instead, convert it to an array first:
// Close all forms except the main one foreach (Form form in Application.OpenForms.Cast<Form>().ToArray()) { if (form != this) // "this" refers to your main form { form.Close(); } }
If you want to close every form (including the main one) and exit the entire application, just use Application.Exit()—it triggers the FormClosing event for all forms before shutting down:
Application.Exit();
For a forced exit (skipping closing events entirely), you can use Environment.Exit(0), but only use this if you're sure you don't need to clean up resources first.
Let's say you open a new form from your main form and don't need the main form anymore. The easiest way is to subscribe to the new form's FormClosed event, then close the main form when that event fires:
// Inside your main form's button click (or wherever you open the new form) private void btnLaunchNewForm_Click(object sender, EventArgs e) { NewForm myNewForm = new NewForm(); // When the new form closes, shut down the main form myNewForm.FormClosed += (senderObj, eArgs) => { this.Close(); }; myNewForm.Show(); this.Hide(); // Optional: Hide the main form so users don't see it anymore }
Another option is to make the new form your application's main form. This way, closing it will automatically exit the entire app (and close the original main form if you handle it right):
NewForm myNewForm = new NewForm(); // Replace the main form with the new one Application.Run(myNewForm); // Close the original main form now that it's no longer needed this.Close();
Just make sure you don't have any critical resources tied to the original main form before closing it.
内容的提问来源于stack exchange,提问作者Pedro Filipe

