Splash Screen 加载窗体
对于windows开 发人员来说在打开VS开发工具时,总是先呈现一个SplashScreen界面,登上几秒钟后才打开VS的主界面。这样的效果一般是在主界面需要加载大量 资源,为避免主界面变成“死”界面,而提供一个友好的Loading画面。为实现该效果,我们通常在加载主界面Application.Run(new MainForm())之前打开一个SplashScreen窗口,并在SplashScreen窗口中加载数据。
微软提供了WindowsFormsApplicationBase类,该类提供了SplashScreen属性,及 OnCreateSplashScreen虚方法的接口。在实现自己的SplashScreen窗口时,主要重载 OnCreateSplashScreen方法,并创建一个Form对象,赋值给SplashScreen属性,并且该类还提供了 MinimumSplashScreenDisplayTime属性,用于设置SplashScreen窗口的呈现时间。当然你可以自己控制 SplashScreen窗口的呈现和关闭。
1. 实现Application类首先我们需要实现WindowsFormsApplicationBase的基类SplashScreenApplication,并重新定义OnCreateSplashScreen方法。
WindowsFormsApplicationBase 类是位于Microsoft.VisualBasic.ApplicationServices命名空间下,需要添加 Microsoft.VisualBasic.dll引用。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualBasic.ApplicationServices; namespace Test_Splash_Screen { internal sealed class SplashScreenApplication : WindowsFormsApplicationBase { public SplashScreenApplication() { base.IsSingleInstance = true; base.EnableVisualStyles = true; base.MinimumSplashScreenDisplayTime = 2000; } protected override void OnCreateMainForm() { this.MainForm=new Main_Form(); //base.OnCreateMainForm(); } protected override void OnCreateSplashScreen() { this.SplashScreen = new SplashScreenForm(); //base.OnCreateSplashScreen(); } } }
其中Main_Form为主窗口,SplashScreenForm为Loading窗口,,并设置2000毫秒SplashScreen自动关闭,并试图打开主窗体。
Application会首先执行OnCreateSplashScreen方法,然后执行OnCreateMainForm窗口。需要注意的是,2000毫秒并不是两个方法的执行的时间间隔,而是主窗体创建2000毫秒后才关闭SplashScreen窗体,并显示主窗体。这里的 SplashScreenForm不能用于加载数据,因为2000毫秒结束就会关闭,我们不能保证SplashScreen可以在2000毫秒吧数据加载完成。
2. 实现加载效果这里SplashScreen的目的是加载数据,而不是简单的友好效果,因此简单的2000毫秒不能达到我们加载数据的需求。鉴于此,我们需要自己控制 SplashScreen界面,当数据加载完成后才能关闭SplashScreen窗口,并显示主界面。
为达到加载数据的效果,这里会在 SpashScreen界面显示加载数据的过程。代码如下:
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Threading; using Microsoft.VisualBasic.ApplicationServices; namespace Test_Splash_Screen { internal sealed class SplashScreenApplication2 : WindowsFormsApplicationBase { public ManualResetEvent resetEvent = new ManualResetEvent(true); public void SplashScreenApplication2() { base.IsSingleInstance = true; base.EnableVisualStyles = true; } protected override void OnCreateMainForm() { if (resetEvent.WaitOne()) { this.MainForm = new Main_Form(); } } protected override void OnCreateSplashScreen() { this.SplashScreen = new SplashScreenForm(); } } }
View Code为演示加载过程,SplashScreenForm还负责了加载数据:
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/61886.html
- 上一篇:WinForm上显示gif动画:转
- 下一篇:C#读取文本播放相应语音【转】