tags:

views:

3321

answers:

2

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?

A: 

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?

bendewey
That doesn't work either. And the Startup event args take StartupEventArgs.
Ray
Nothing malicious, on a separate thread I am checking if a .XAML file has been updated. If it has I want to reload the main window using XamlReader.Load(fileStream);
Paul
+7  A: 

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

Ray
Thank you!I had this problem with a modal login dialog being shown and then WPF quitting without any message or exceptions before the main window would display.
Andy Dent