0

Possible Duplicate:
Windows Forms: Change application mainwindow at runtime

I want to create new form, and destroy main form in c#. How i can do this?

var fw2 = new Form2();
fw2.Show();
this.Dispose();

This code just show second form for a one second and close my program. Any ideas?

Community
  • 1
  • 1
Yozer
  • 648
  • 1
  • 11
  • 26
  • The main message pump is attached to the first form, most likely, so closing it closes the pump, which then goes on to exit `Main` - closing the primary thread. Instead of closing the first form, a quick option would be to `Hide` it. – Adam Houldsworth Jan 16 '13 at 10:24
  • Ok, i can use this.Hide() instead this.Dispose() then it works. But i have to call Enviorment.Exit(0), when user want to Close second form. – Yozer Jan 16 '13 at 10:26
  • You could have the first form subscribe to the second forms `Closed` event, and on `Closed` close form 1. – Adam Houldsworth Jan 16 '13 at 10:26

1 Answers1

0

I have done this sort of thing in the Program class. I just put the below code normally seen in the Main method into a loop.

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());

Once the main form has closed the code leaves the 'Run' method and goes into a loop which checks a application global variable to see if it needs to render a new form.

This is over kill if you just want to open a new form but it seems to work quite well if you are regularly 'swapping' your main form in and out.

My code looks (a little) like this...

while (true)
{
    if (AppSettings.SomeFormSettng = FormSetting.ShowAnotherForm)
    {
        Form showThisForm = AppSettngs.TheForm;
        if (ThisIsTheFirstRun)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            ThisIsTheFirstRun = false;
        }
        Application.Run(new showThisForm ());
    }
    else
    {
        return;
    }
}
Jammerz858
  • 1,605
  • 3
  • 14
  • 14