WPF SplashScreen 何时关闭?

When does the WPF SplashScreen close?

我正在制作自定义启动画面(因为 standard one 不符合我的需要)。但是我想从中获得一个选项——自动关闭。但是要实现它,我需要了解常见的 SplashScreen 如何选择关闭的时刻。

那么,是否有任何类型的事件可以向启动画面发送消息,告诉它应该关闭它?普通启动画面至少使用什么事件?

您可以通过在应用程序的 OnStartup 事件处理程序中自行创建和显示来更好地控制启动画面,而不是将生成操作设置为启动画面的图像文件。 SplashScreen 的 show 方法有一个参数来阻止它自动关闭,然后你可以使用 Close 方法告诉它什么时候关闭:

首先从 App.xaml 中删除 StartupUri 标签:

<Application x:Class="Splash_Screen.App" 
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Application.Resources> 

    </Application.Resources> 
</Application>

将图像文件的 Build Action 更改为 Resource

然后在 OnStartup 事件处理程序中创建并显示初始屏幕:

public partial class App : Application 
    { 
        private const int MINIMUM_SPLASH_TIME = 1500; // Miliseconds 
        private const int SPLASH_FADE_TIME = 500;     // Miliseconds 

        protected override void OnStartup(StartupEventArgs e) 
        { 
            // Step 1 - Load the splash screen 
            SplashScreen splash = new SplashScreen("splash.png"); 
            splash.Show(false, true); 

            // Step 2 - Start a stop watch 
            Stopwatch timer = new Stopwatch(); 
            timer.Start(); 

            // Step 3 - Load your windows but don't show it yet 
            base.OnStartup(e); 
            MainWindow main = new MainWindow(); 

            // Step 4 - Make sure that the splash screen lasts at least two seconds 
            timer.Stop(); 
            int remainingTimeToShowSplash = MINIMUM_SPLASH_TIME - (int)timer.ElapsedMilliseconds; 
            if (remainingTimeToShowSplash > 0) 
                Thread.Sleep(remainingTimeToShowSplash); 

            // Step 5 - show the page 
            splash.Close(TimeSpan.FromMilliseconds(SPLASH_FADE_TIME)); 
            main.Show(); 
        } 
    }

WPF SplashScreen class 使用了一个非常简单的技巧,它调用 Dispatcher.BeginInvoke().

预期 UI 线程正在努力初始化程序,因此不会调度任何内容。是"hung"。当然不是永远,一旦完成,它就会重新进入调度程序循环,现在 BeginInvoked 方法有机会,ShowCallback() 方法运行。命名不当,应该是 "CloseCallback" :) 0.3 秒的淡入淡出掩盖了让主要 window 渲染的任何额外延迟。

一般来说,在 UI 线程上调用 Dispatcher.BeginInvoke() 看起来很奇怪,但非常有用。解决重入问题的好方法。

很简单,不是唯一的方法。 window 的主要加载事件可能是一个有用的触发器。