VS WinForm实现按钮打开10个Form2线程及关闭后可重开的问题
Fixing Your WinForms Multi-Form Management
Hey there! Let's get this sorted out. The issue with your current code is that you're only creating one instance of Form2, so clicking runbtn only opens one window, and once you close it with stopbtn, that instance is disposed—you can't reuse it to show again. Here's how to adjust your code to handle 10 Form2 windows, properly close them all, and let runbtn work again after closing:
Step-by-Step Solution
- Store all Form2 instances in a collection (like a
List<Form2>) so we can track and manage them. - Create 10 new Form2s when
runbtnis clicked, add each to the list, and show them. - Close all Form2s when
stopbtnis clicked, then clear the list (so we can create new ones later). - Handle manual window closure: If a user closes a Form2 by clicking its X button, remove that instance from our list to avoid invalid references.
Modified Code
namespace WindowsFormsApp1 { public partial class Main : Form { // Collection to keep track of all Form2 instances private List<Form2> _form2Instances = new List<Form2>(); public Main() { InitializeComponent(); } private void runbtn_Click(object sender, EventArgs e) { // Only create new forms if none are open (prevents duplicate sets) if (_form2Instances.Count == 0) { for (int i = 0; i < 10; i++) { Form2 newForm = new Form2(); // Remove the form from our list when it's closed manually newForm.FormClosed += (s, args) => _form2Instances.Remove(newForm); _form2Instances.Add(newForm); newForm.Show(); } } } private void stopbtn_Click(object sender, EventArgs e) { // Iterate over a copy of the list to avoid modification errors during loop foreach (var form in _form2Instances.ToList()) { form.Close(); } // Clear the list to reset for future runs _form2Instances.Clear(); } } }
Key Explanations
_form2InstancesList: This acts as a registry for every Form2 we create, so we can access and close all of them when needed.runbtn_ClickLogic: The check for an empty list ensures we don't open multiple overlapping sets of 10 forms. We loop 10 times to create new Form2 instances, attach aFormClosedhandler to clean up our list if a user closes a window manually, then add each form to the list and show it.stopbtn_ClickLogic: UsingToList()creates a copy of the list before iterating—this avoids errors because closing a form triggers theFormClosedevent which modifies the original list. After closing all forms, we clear the list so the nextrunbtnclick can spawn a fresh set of 10 windows.
This setup lets you open 10 Form2 windows, close all of them with stopbtn, and click runbtn again to start over without any issues.
内容的提问来源于stack exchange,提问作者4nbu01
相关产品推荐
相关产品推荐

