Dmytro Tysko
Dmytro Tysko

Reputation: 73

WPF application closes when I close Splash Screen

I want to add a splash screen to my WPF app in a new thread (because my animated splash screen hangs when the data for Main window is loading). Code:

SplashScreenWindow splashScreenWindow = null;
Thread newWindowThread = new Thread(() =>
{
    splashScreenWindow = new SplashScreenWindow();
    splashScreenWindow.ShowDialog();
});
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();

   data loading...

_mainWindow.Show();
splashScreenWindow.Close();

My problem is that the program closes when I close the splash screen.

Upvotes: 0

Views: 656

Answers (2)

metalmonkey
metalmonkey

Reputation: 488

I have done something similar, this works for me.

SplashScreenWindow splashScreenWindow = null;
Thread newWindowThread = new Thread(() =>
{
    splashScreenWindow = new SplashScreenWindow();
    splashScreenWindow.Show();
    System.Windows.Threading.Dispatcher.Run();
});
newWindowThread.SetApartmentState(ApartmentState.STA);
newWindowThread.IsBackground = true;
newWindowThread.Start();

data loading...

_mainWindow.Show();

You are calling the close too early, call the splashScreenWindow.Close() from the main window Loaded event.

_mainWindow.Loaded += (s,ev) => { 
splashScreenWindow.Dispatcher.Invoke(new Action(.splashScreenWindow.Close));
};

Upvotes: 2

FakeCaleb
FakeCaleb

Reputation: 993

Because .Show() is not a blocking call meaning it will return regardless to the window actually closing, so the application will run out to the end more than likely.

Use .ShowDialog().

Make sure you close the splash screen before calling this.

Upvotes: 1

Related Questions