0

So I have put both the forms in the Program.cs so I can close them without ending the application. But once I close both of them the application ends, even when I open the other one back up.

Program.cs code:

Application.Run(new Form1());

Application.Run(new Form2());

I have a button on Form1 that opens Form2 and closes Form1

public Form1()
{
    InitializeComponent();
}

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

And then I have done the same on Form2 (open Form1 and close Form2)

public Form2()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    Form1 Form1 = new Form1();
    Form1.Show();
    this.Close();
}

If I press on the button on Form1, Form2 will open, but once I try come back it closes the whole Application. Now I know this.Hide() works but I need the forms to close, not hide. I have a way to make it work: By adding a 3rd form into Program.cs and then hiding it upon loading, but I wondered if there was a way to do it without the 3rd form.

Community
  • 1
  • 1
  • Are you trying to achieve a Wizard-like behaviour? If so, you can take a look at the Wizard Design Pattern. It's explained here: http://ui-patterns.com/patterns/Wizard – mororo Aug 22 '18 at 09:29

1 Answers1

0

Change

this.Close();

To:

this.Hide();

Because you can't Close Main Application window and want to application runs after it. You must hide main form or change main window to window who was still opened.

In this case you must close main window after ShowDialog() was ended. Then you must add on the end of this button event function this.Close()

Ido H Levi
  • 181
  • 9