【实战学习c#】设置Windows应用程序的启动窗体

实战说明


我们使用c#编写的程序往往由多个窗体共同组成,运行时要有一个启动窗体(即第一个运行的窗体),本实例将详细说明如何设置Windows应用程序的启动窗体。

预备知识


设置启动窗体主要用到了Appilication类中的Run方法。Application类提供了Static方法和属性以管理应用程序,如启动和停止应用程序、处理Windows消息的方法和获取应用程序信息的属性等,而Run方法用来在当前线程上开始运行标准应用程序消息循环,该方法为可重载方法,它有3种重载形式,分别如下:

1 public static void Run()
2 public static void Run(AppilicationContext context)
3 public static void Run(Form mainForm)

参数说明:

context:一个ApplicationContext,应用程序将在其中运行。

mainForm:一个Form,它代表要使之可见的窗体。

实战演练


1、打开Visual Studio 2015开发环境,新建一个窗体应用程序,并将其命名为SetStartForm;

2、在“解决方案资源管理器中”单击右键--【添加】--【Windows窗体】,保持其原有名Form2;

3、在“解决方案资源管理器”中,找到Peogram.cs,双击打开该文件,此时即可修改其中的Appication.Run方法。本例修改Form2为启动窗体(文中第二处注释处),代码如下所示。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using System.Windows.Forms;
 6 
 7 namespace SetStartForm
 8 {
 9     static class Program
10     {
11         /// <summary>
12         /// 应用程序的主入口点。
13         /// </summary>
14         [STAThread]
15         static void Main()
16         {
17             Application.EnableVisualStyles();
18             Application.SetCompatibleTextRenderingDefault(false);
19             Application.Run(new Form2());//即修改此句,本例将启动窗体改为了Form2
20         }
21     }
22 }

总结


Main方法是C#程序的主入口点,每个C#程序都包含一个Main方法,Windows窗体应用程序中Main方法存在于Program.cs文件中,在该方法中,可以编写程序启动时需要用到的C#代码。