2
votes

Assuming two projects, a WinForms project and a WPF project, in the WinForms project there is no problem with the following code being in Main() and removing the Application.Run:

        while (true)
        {
            Thread.Sleep(1000);
            Form1 window = new Form1();
            window.Show();
            Thread.Sleep(1000);
            window.Close();
        }

However, in the WPF application, removing the StartupUri="Window1.xaml" and then creating:

    public App()
    {
        while (true)
        {
            Thread.Sleep(1000);
            Window window = new Window();
            window.Show();
            Thread.Sleep(1000);
            window.Close();
        }
    }

The program loops indefinitely but the Window only opens up once?

2

2 Answers

9
votes

You need to change the ShutdownMode like so

public App()
{
    this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
    while (true)
    {
        Thread.Sleep(1000);
        Window window = new Window();
        window.Show();
        Thread.Sleep(1000);
        window.Close();
    }
    //Will never get here with this sample code,
    //but this would be how you close the app.
    this.Shutdown();

}

Otherwise WPF treats closing the first window opened as shutting down the application. Although the code in the loop will continue to run.

The lifetime of some applications may not be dependent on when the main window or last window is closed, or may not be dependent on windows at all. For these scenarios you need to set the ShutdownMode property to OnExplicitShutdown, which requires an explicit Shutdown method call to stop the application. Otherwise, the application continues running in the background.

MSDN:ShutdownMode Property

0
votes

Traditionally if you remove the StartupUri you should load the MainWindow in the Application.Startup event

public App() 
{
  Startup += App_Startup
}

public void App_Startup(object sender, StartupEventArgs e)
{
  while (true)
  {
    Thread.Sleep(1000);
    MainWindow = new Window();
    MainWindow.Show();
    Thread.Sleep(1000);
    MainWindow.Close();
  }
}

Although, I'm not sure if this will work either. What exactly are you trying to do?