Search code examples
c#.netwinformsmainwindow

Windows Forms: Change application mainwindow at runtime


Normally I would do Application.Run(myMainForm).

But I want to do something like this:

MyForm1 f = new MyForm1();
f.Close+=OnOpenOverviewWin();
Application.Run(f);

void OnOpenOverviewWin()
{
MyOverViewForm f = new MyOverViewForm ();
Application.Run(f); // i want to do this
Application.NewMainWindow = f; // or something like that
}

Solution

  • Set the Application.ShutdownMode property to ShutdownMode.OnLastWindowClose

    MyForm1 f = new MyForm1();
    f.Close += OnOpenOverviewWin();
    Application.ShutdownMode = ShutdownMode.OnLastWindowClose;
    Application.Run(f);
    
    void OnOpenOverviewWin()
    {
      MyOverViewForm f = new MyOverViewForm ();
      f.Show();
    }