How to Open a New Form and Close the Current Form in C#
When developing C# applications, you may encounter situations where you need to open a new form from a button in the current form, close the current form, and focus on the newly opened form. Here's how you can achieve this:
Steve's Solution
One common approach is to use the following code:
private void Button1_Click(object sender, EventArgs e) { var form2 = new Form2(); form2.Show(); this.Close(); }
However, this solution has a flaw. When this.Close() is called, both the current form and the newly opened form (form2) are disposed. To prevent this, you should consider hiding the current form instead of closing it.
Corrected Solution
To Open a New Form and Close the Current Form, use the following code:
private void OnButton1Click(object sender, EventArgs e) { this.Hide(); var form2 = new Form2(); form2.Closed += (s, args) => this.Close(); form2.Show(); }
In this corrected solution:
This approach ensures that the new form (Form2) is open and focused, while the current form (Form1) is hidden and subsequently closed.
The above is the detailed content of How to Properly Open a New Form and Close the Current Form in C#?. For more information, please follow other related articles on the PHP Chinese website!