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

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

DDD
Release: 2025-01-06 13:04:41
Original
961 people have browsed it

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

Opening a New Form and Closing the Current Form in C#

When navigating through an application, it may be necessary to open a new form and close the current one. This can be achieved through a series of steps:

Opening a New Form

  • From within the current form, create an instance of the new form class.
  • Display the new form using the Show() method.

Closing the Current Form

  • Before closing the current form, it's recommended to hide it rather than disposing it. This allows for a smooth transition to the new form.
  • To hide the current form, use the Hide() method.

Focusing on the New Form

  • After the current form is hidden, the new form should be activated and brought to the foreground.
  • This can be achieved using the Show() method with the additional parameter false, which specifies that the form should not be activated.
  • Subsequently, the Activate() method should be called on the new form to focus on it.

Example Implementation

The following code snippet demonstrates how to open a new form (Form2) and close the current form (Form1) in C# using the steps described above:

private void OnButton1Click(object sender, EventArgs e)
{
    this.Hide();
    var form2 = new Form2();
    form2.Closed += (s, args) => this.Close();
    form2.Show(false);
    form2.Activate();
}
Copy after login

The above is the detailed content of How to 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template