0
votes

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.

2
You know you can just add an image to your project, set it's Build Action to "Splash Screen" and the framework will take care this for you, right?Mark Feldman
My splash screen isn't an image. It's a window that has an animation.Dmytro Tysko

2 Answers

2
votes

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));
};
1
votes

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.