WPF Application

Application类作为启动的入口,在VS中,通常自动代码为我们继承了Application类,这样做的有点,我还没有理解到,但是我们先学到这个知识点。

为了能够更好的控制整个启动过程,包括得到Active,LoadComplete,Deactive,SessionEnding等事件,可以主动改变程序的入口,即是static void Main(string[] args)方法的所在位置。

我们主动添加一个Program.cs(当然叫别的名字是可以的)的文件,添加Main方法,并在其中修改启动,代码就可以了。说的比较粗略,看代码吧。

Program.cs

 1 using System;
 2 
 3 namespace LearnWPF
 4 {
 5     class Program
 6     {
 7         [STAThread]
 8         public static void Main(string[] args)
 9         {
10             App app = new App();
11             myWInd m = new myWInd();
12             app.MainWindow = m;
13             m.Show();
14             app.Run();
15         }
16     }
17 }

App.xaml.cs

 1 using System;
 2 using System.Diagnostics;
 3 using System.Windows;
 4 
 5 namespace LearnWPF
 6 {
 7     /// <summary>
 8     /// Interaction logic for App.xaml
 9     /// </summary>
10     public partial class App : Application
11     {
12         protected override void OnActivated(EventArgs e)
13         {
14             base.OnActivated(e);
15             Debug.WriteLine("OnActived");
16         }
17 
18         protected override void OnDeactivated(EventArgs e)
19         {
20             base.OnDeactivated(e);
21             Debug.WriteLine("OnDeactived");
22         }
23 
24         protected override void OnExit(ExitEventArgs e)
25         {
26             base.OnExit(e);
27             MessageBox.Show("Exiting");
28         }
29 
30         protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
31         {
32             base.OnSessionEnding(e);
33             MessageBox.Show("you're quitting");
34         }
35 
36         protected override void OnStartup(StartupEventArgs e)
37         {
38             base.OnStartup(e);
39             MessageBox.Show("Staring");
40         }
41 
42         protected override void OnLoadCompleted(System.Windows.Navigation.NavigationEventArgs e)
43         {
44             base.OnLoadCompleted(e);
45             MessageBox.Show("completed");
46         }
47     }
48 }

App.xaml 这文件指明了启动的窗口等内容,所以需要相应地修改。

1 <!--application 的 class属性可以随便写-->
2 <!--application 的 StartupUri属性指明了 启动的窗体-->
3 <Application x:Class="muhaha"
4              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
5              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
6     <Application.Resources>
7 
8     </Application.Resources>
9 </Application>

但是,到了这里还是不行的;因为对于App.xaml在自动生成的代码里,会有Main方法入口,因此还需要改变程序的入口,在项目的属性里修改配置。请注意,刚刚添加Program.cs文件后,可能这里不会有,编译一次,就会在这里出现了,如下图所示。

希望能够帮助一些同学。

原文地址:https://www.cnblogs.com/warnet/p/5049991.html