且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF:如何为程序添加splashScreen(初始屏幕)

更新时间:2022-08-18 13:26:42

原文:http://www.cnblogs.com/chenxizhang/archive/2010/03/25/1694606.html

官网:

https://msdn.microsoft.com/zh-cn/library/system.windows.splashscreen%28v=vs.100%29.aspx

https://msdn.microsoft.com/zh-cn/library/cc656886%28v=vs.100%29.aspx

 

考虑到大部分的splashscreen其实都只是一个图片,所以最简单的做法是,先导入一张图片,然后设置它的生成操作为“splash screen”

WPF:如何为程序添加splashScreen(初始屏幕)

注意,其他什么都不要做,此时运行程序的话,就可以看到效果

WPF:如何为程序添加splashScreen(初始屏幕)

注意:虽然我们的图片是gif的格式,但显示出来的效果却是静态的。

 

那么,到底发生了什么,让他具有了这个特性呢?我们可以打开项目的文件,就是那个csproj文件

WPF:如何为程序添加splashScreen(初始屏幕) 

原来它是通过在项目文件中声明一个SplashScreen来实现的。

[注意]这个文件是给msbuild这个工具用的。

[思考]所以试想一下,一个应用程序是否可以有多个SplashScreen呢?

 

同时,我们还可以打开IL代码来了解一下,

WPF:如何为程序添加splashScreen(初始屏幕)

从上面的il代码可以很直观地看出来,其实它是先实例化了一个SplashScreen,然后调用了它的Show方法而已。

如果是这样的话,我们当然也可以自己写代码来实现

首先,让我们将图片的生成操作修改为“嵌入的资源”

WPF:如何为程序添加splashScreen(初始屏幕)

然后通过下面的代码就可以实现功能

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;

namespace WpfApplication1
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            SplashScreen s = new SplashScreen("20080320132823923.gif");
            s.Show(true);

            base.OnStartup(e);
        }
    }
}

值得一提的是,目前看来,也没有办法加载一个窗口作为SplashScreen。

如果希望闪屏至少显示多少时间,则可以考虑下面的代码

            SplashScreen s = new SplashScreen("20080320132823923.gif");
            s.Show(false);
            s.Close(new TimeSpan(0, 0, 10));