4

I'd like to restart my main form on clicking a button. For instance:

In program.cs:

Application.Run(new MainForm(data))

In MainForm.cs:

private void btn1_Click(object sender, EventArgs e)
{
    MainForm newForm = new MainForm(newData);
    this.close();
    Application.Run(newForm);
}

So that my new Main window is the new instance of MainForm. How can I do that in a way such that the first instance is cleared from memory?

EDIT I.e. I'd like my first instance of MainForm to completely disappear - is that the same as just calling this.Hide()? Or calling this.Close() and then setting it up so that the application exits only when the last window is closed, and not when the main window is closed?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
user2635088
  • 1,598
  • 1
  • 24
  • 43

2 Answers2

2

No. Starting a second message loop on a single thread is not a valid operation. You can use Form.ShowDialog instead:

Hide();
MainForm newForm = new MainForm(newData);
newForm.Closed += (s, args) => Close();
newForm.ShowDialog();

Or if you'd like to close the old instance:

Hide();
MainForm newForm = new MainForm(newData);
newForm.ShowDialog();
Close();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
-1

"Is that possible"?

No.
Generally, you should run a sample and test. Then you'll answer the question yourself
You'll want to do something like:

private void button_click(object sender, RoutedEventArgs e)
{
    NextWindow window = new NextWindow();
    window.Show();
    this.Close();
}
dimitar.bogdanov
  • 387
  • 2
  • 10
Acha Bill
  • 1,255
  • 1
  • 7
  • 20