0

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

Jim
  • 2,974
  • 2
  • 19
  • 29
jstdenis
  • 11
  • 2
  • 2
    Pass the original form as a variable to the second one, you need it stored to be able to call it again - in the `Form2` constructor `Form2(Form1 x)` and store it as a variable, then when you want to reopen it you can call it from `Form2`'s variable – Alfie Goodacre Nov 08 '16 at 16:48
  • Possible duplicate of [Windows forms spinning in c#](http://stackoverflow.com/questions/3666604/windows-forms-spinning-in-c-sharp) – Ahmet Kakıcı Nov 08 '16 at 16:57
  • x.FormClosing += (s, cea) => { if (!cea.Cancel) this.Show(); }; Do look at the way other programs do this, they rarely swap windows. Using a single main window that swaps its content is the normal UI. You'd get there by creating UserControls instead of Forms. – Hans Passant Nov 08 '16 at 17:43

2 Answers2

1

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();
}
Christian
  • 394
  • 2
  • 17
-1

Do this:

private void button1_Click(object sender, EventArgs e)
    {
        Form2 x = new Form2();
        this.Hide();
        x.ShowModal();
        this.Show();
    }
Kell
  • 3,252
  • 20
  • 19