WPF 显示初始化界面

今天在看《WPF编程宝典》时,看到了Application类,该类可以做很多事情,我认为比较实用的是显示初始化界面,因为之前有个项目在打开的时候要加载好多dll,非常耗时,让客户等的蛋疼,还好那个项目处在试用期,今天决定修改一下。  

  步骤如下:

      1.为项目添加一个文件;

  2.在解决方案中(Solution Explore)选择该文件;

  3.在属性窗口将生成操作(Build Action)改为 SplashScreen;

  

  生成运行,通过。

  这样应该就完成了。其实我是在写博客的时候才发现这样就已经可以达到想要的效果了。我之前还跑去找Main()方法,把Main方法写在App.xaml.cs文件里,在Main方法中手动写SplashScreen 代码,最终也能实现效果,在这个过程中也有一点点收获,顺便把过程记录下来吧,以备复习。

  首先找到项目所在目录,打开obj/Debug/App.g.cs,会发现Main方法的定义:

  

  

 1 /// <summary>
 2         /// Application Entry Point.
 3         /// </summary>
 4         [System.STAThreadAttribute()]
 5         [System.Diagnostics.DebuggerNonUserCodeAttribute()]
 6         [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
 7         public static void Main() {
 8             //这里就是初始化界面 效果
 9             SplashScreen splashScreen = new SplashScreen("screen.jpg");
10             splashScreen.Show(true);
11 
12             WPFApplication.App app = new WPFApplication.App();
13             app.InitializeComponent();
14             app.Run();
15         }
View Code

  但是这个Main是自动生成的,如果想要再里面添加自己的代码,怎么办呢。网上有人说直接编写App.g.cs文件,我没试过,据说可行,但是下次打开项目,App.g.cs文件又要重新生成,这样很麻烦。

  解决办法就是,在我们项目的App.xml.cs文件编写代码,并且不去生成App.g.cs文件。

  操作如下:选中App.xaml,查看属性,将生成操作改成Page:

  

  生成,然后再去看obj/Debug/App.g.cs,发现不见了Main方法。

  此时,我们在项目中打开App.xaml.cs,添加如下代码:

   

 1        [STAThread()]
 2         public static void Main()
 3         {
 4             //初始化界面时显示的图片
 5          SplashScreen screen = new SplashScreen("Images/screen.jpg");
 6             screen.Show(true);
 7              
 8             //在这里编写其他逻辑..............
 9 
10             WeaponrySystem.App app = new App();
11             app.InitializeComponent();
12             app.Run();
13         }    
View Code

 
  当然,在Main方法中也可以添加其他逻辑代码,比如时间限制,硬件检测等。  

  参考:1.《WPF编程宝典》

       2.http://www.cnblogs.com/yigedaizi/archive/2011/06/16/WPFapp_g_cs.html

    

  

  

原文地址:https://www.cnblogs.com/guzhongx/p/3287072.html