Home > Backend Development > C++ > How to Properly Open a New Form and Close the Current Form in C#?

How to Properly Open a New Form and Close the Current Form in C#?

Linda Hamilton
Release: 2025-01-06 13:17:39
Original
709 people have browsed it

How to Properly Open a New Form and Close the Current Form in C#?

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();
}
Copy after login

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();
}
Copy after login

In this corrected solution:

  • this.Hide() hides the current form.
  • A new Form2 instance (form2) is created and shown.
  • An event handler is added to the Closed event of form2. This event handler calls this.Close() when form2 is closed, ensuring that the current form is closed only after the new form is closed.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template