WPF Splash Screen With Minimum Duration
How to make a splash screen appear for a minimum duration with very little code
Introduction
Splash screens are easy to add to WPF applications, but allow for little flexibility. In particular, you cannot specify a minimum duration that a splash screen can appear for. Such a minimum duration can be desirable to ensure users on faster and slower PCs have a similar loading experience. A minimum duration can also ensure that users on fast PCs do not simply see the screen flash as the splash appears and vanishes. This tip shows how to simply and cleanly show a SplashScreen
for a minimum period of time, without resorting to sleeping threads or other hackish solutions.
Using the Code
To specify a minimum showing duration, we inherit from the SplashScreen
class and provide a new Show()
method:
public class SplashScreen2 : SplashScreen
{
private DispatcherTimer dt;
public SplashScreen2(string resourceName)
: base(resourceName)
{ }
/// <summary>
/// Shows the splash screen
/// </summary>
/// <param name="minDur">The minimum duration this splash should show for</param>
/// <param name="topmost">True if the splash screen should appear
/// top most in windows. Recommended to be true, to ensure it does not appear
/// behind the loaded main window</param>
public void Show(TimeSpan minDur, bool topmost = true)
{
if (dt == null) //prevent calling twice
{
base.Show(false, topmost);
dt = new DispatcherTimer(minDur, DispatcherPriority.Loaded,
CloseAfterDelay, Dispatcher.CurrentDispatcher);
}
}
private void CloseAfterDelay(object sender, EventArgs e)
{
dt.Stop();
Close(TimeSpan.FromMilliseconds(300));
}
}
The Show
method above shows the SplashScreen
but states that it will manually close itself. It then starts a new DispatcherTimer
, which will call CloseAfterDelay
when both:
- The
timespan
has completed AND - The application has loaded.
To use the new SplashScreen2
:
- Add an image to your WPF project. Under properties for your image, change 'Build Action' to 'Resource'. Do not set it to
SplashScreen
, because this will insert unwanted code into yourMain[]
method. - In App.cs, create and show a new
SplashScreen2
in the constructor, specifying the minimum duration you wish it to show for:
public App()
{
SplashScreen2 splash = new SplashScreen2("my_splash_image.jpg");
splash.Show(TimeSpan.FromSeconds(2));//Show for at least 2 seconds min duration
}
History
- April 14 2013: Project submitted.