65.9K
CodeProject 正在变化。 阅读更多。
Home

带有最小持续时间的 WPF 启动画面

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3投票s)

2013年4月14日

CPOL

1分钟阅读

viewsIcon

23973

如何使用极少的代码使启动画面显示最小持续时间

引言

为WPF应用程序添加启动画面很容易,但灵活性较小。特别是,你无法指定启动画面必须显示的最小持续时间。 这样的最小持续时间可能是有益的,以确保使用较快和较慢的PC的用户具有相似的加载体验。 最小持续时间还可以确保快速PC的用户不会仅仅看到屏幕闪烁,因为启动画面出现并消失。 本技巧展示了如何简单而干净地显示一个SplashScreen,持续最小时间,而无需使用休眠线程或其他临时解决方案。

Using the Code

要指定最小显示持续时间,我们从SplashScreen类继承并提供一个新的Show()方法

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

上面的Show方法显示了SplashScreen,但声明它将手动关闭自身。 然后,它启动一个新的DispatcherTimer,当且仅当

  1. timespan时间跨度完成,并且
  2. 应用程序已加载时,才会调用CloseAfterDelay

要使用新的SplashScreen2

  1. 将图像添加到你的WPF项目中。 在图像的属性中,将“Build Action”(生成操作)更改为“Resource”(资源)。 不要将其设置为SplashScreen,因为这会将不需要的代码插入到你的Main[]方法中。
  2. App.cs中,在构造函数中创建并显示一个新的SplashScreen2,指定你希望它显示的最小持续时间
public App()
{
    SplashScreen2 splash = new SplashScreen2("my_splash_image.jpg");
    splash.Show(TimeSpan.FromSeconds(2));//Show for at least 2 seconds min duration
}

历史

  • 2013年4月14日:项目提交。
© . All rights reserved.