WPF溅屏何时关闭?
本文关键字:何时关 WPF | 更新日期: 2023-09-27 18:06:48
我正在制作一个自定义的闪屏(因为标准的不适合我的需求)。但有一个选项我想从它-自动关闭。但是要实现它,我需要了解常见的SplashScreen
如何选择关闭时刻。
那么,是否有任何类型的事件来通知启动屏幕,告诉它应该关闭?最常见的溅屏使用的是什么事件呢?
WPF SplashScreen类使用了一个非常简单的技巧,它调用Dispatcher.BeginInvoke()。
预期是UI线程正在努力初始化程序,因此没有调度任何东西。它是"挂"。当然不是永远,一旦它完成,它就会重新进入分派器循环,现在BeginInvoked方法得到了一个机会,ShowCallback()方法运行。名字不好,应该是"CloseCallback":)0.3秒的淡出掩盖了主窗口渲染的任何额外延迟。
一般来说,在UI线程上调用Dispatcher.BeginInvoke()看起来很奇怪,但非常有用。这是解决重入问题的好方法。
非常简单,但不是唯一的方法。主窗口的Load事件可以是一个有用的触发器。
你可以通过在应用程序的OnStartup事件处理程序中创建和显示它来更好地控制闪屏,而不是将Build Action设置为闪屏。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
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();
}
}