Home > Back-end >  Conditionally changing a SplashScreen image during runtime
Conditionally changing a SplashScreen image during runtime

Time:05-18

I have an existing image showing as a splash screen when my application is loading. I followed:

How to: Add a Splash Screen to a WPF Application

I set an image's Build Action to 'SplashScreen' (I'll call this the "built-in" way of doing a splash screen). Everything is working well and my image is showing during application load.

Now, I'd like to dynamically change between two different static images - depending on whether a condition (decided at runtime) has been met.

I've tried adding a second image and setting its Build Action to 'SpashScreen', but this creates several build errors (none of them seem to directly relate to the image property change). I could also create a custom Window and display it manually, but this seems to cause a delay that the built-in splash screen doesn't have. The built-in functionality also works well on all resolutions.

Is there a way to change between different splash screen images, depending on a condition?

CodePudding user response:

The MSBuild action is a simplified way of setting a splash screen.

However, you can also create it manually through code to have more control over when it is shown and when it is closed. You can simply create an instance of the SplashScreen type and pass the path to an image in your project or elsewhere.

In this example, I added images and set their BuildAction to Resource. Then I overrode the OnStartup method (you could alternatively add an event handler to the Startup event) and selected the path of the splash screen image depending on a few conditions and finally created an instance of SplashScreen and show it using the Show(bool autoClose) method. The autoClose flag is set to true, so the splash screen is closed as soon as the application is started. If you want to decide yourself when to close it, pass false and call the Close method instead. There is also an overload of Show to make the splash screen the topmost window.

public partial class App : Application
{
   protected override void OnStartup(object sender, StartupEventArgs e)
   {
      string splashScreenPath;
      if (isPiratedVersionOfMyApp)
         splashScreenPath = @"\Resources\PiratedSplashScreen.jpg";
      else if (isMagicVersionOfMyApp)
         splashScreenPath = @"\Resources\MagicSplashScreen.jpg";
      else
         splashScreenPath = @"\Resources\DefaultSplashScreen.jpg";

      SplashScreen splashScreen = new SplashScreen(splashScreenPath);
      splashScreen.Show(true);

      base.OnStartup(e);
      // ...other code.
   }
}
  • Related