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

How to Open a New Form and Close the Current One in C# Without Closing the New Form?

DDD
Release: 2025-01-06 13:16:41
Original
239 people have browsed it

How to Open a New Form and Close the Current One in C# Without Closing the New Form?

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

When creating applications with multiple forms, it's common to need to open a new form while closing the current one. Here's a solution:

Steve's initial approach of calling this.Close() to close the current form does not work as it also disposes of the new form. To avoid this, Steve's solution can be modified to hide the current form instead and handle the Closed event of the new form to call this.Close.

Modified Solution:

private void OnButton1Click(object sender, EventArgs e)
{
    // Hide the current form instead of closing it.
    this.Hide();

    // Create a new instance of form2.
    var form2 = new Form2();

    // Subscribe to the Closed event of form2.
    form2.Closed += (s, args) => this.Close(); 

    // Show the new form.
    form2.Show();
}
Copy after login

This solution ensures that the new form is shown and the current form is closed once the new form is closed. It provides better control over the form lifecycle and allows for a seamless transition between forms.

The above is the detailed content of How to Open a New Form and Close the Current One in C# Without Closing the New Form?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template