简体   繁体   中英

Make the startup form visible again after hiding it

I am trying to create a two-form Windows Application in C#. For simplicity and to help me figure it out before using it elsewhere, I have essentially created a Windows form application with two forms: Form1 and Form2, Form1 showing on startup. At the click of a button, I can get Form1 to "disappear" and Form2:

private void button1_Click(object sender, EventArgs e)
{
    Form2 x = new Form2();
    x.Show();
    this.Hide();
}

And this works great. However, when I want to return to Form1 (by making it visible again) and unload Form2, I am unsure how to proceed with coding Form2 to return the user to Form1 using a button click as well. I'm not sure what to refer to to make that form visible again, instead of having to create a new Form1 and loading it, thereby leaving my original startup form sitting in memory.

Any help you can provide would be awesome! Thanks in advance,

-Jan

As Alfie comment suggests, you need to control your instances of each form somehow.

I'd suggest a static class with two variables. When you start up you link the forms to these public properties in the static class.

something like this:

public static class App {

  public static Form Form1;
  public static Form Form2;

}

on startup or the click method, you'd say something like:

private void button1_Click(object sender, EventArgs e)
{  
    if (App.Form1 != null)
      {
        App.Form1 = new Form1();
      }
    App.Form1.Show();
    App.Form2.Hide();
}

Do this:

private void button1_Click(object sender, EventArgs e)
    {
        Form2 x = new Form2();
        this.Hide();
        x.ShowModal();
        this.Show();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM