Application类(位于System.Windows.Forms命名空间)公开了Run方法,可以调用该方法来调度应用程序进入消息循环。Run方法有三个重载
1、第一个重载版本不带任何参数,比较少使用
2、static void Run(System.Windows.Forms.Form mainForm) 调用这个重载,只需要吧希望作为主窗口的Form实例(包括从Form类派生的类)传递给mianForm参数即可。一旦mainForm关闭,整个消息循环就会退出,Run方法返回,应用程序就会退出。
3、static void Run(System.Windows.Forms.ApplicationContext context) 这是Run方法中重载最灵活的。通常的做法是从ApplicationContext类派生,并写入实现代码。ApplicationContext类也允许设置一个Form实例制作为主窗口,也可以不设置主窗口。这个Run方法会在ApplicationContext对象进行消息循环。调用ApplicationContext类的ExitThread方法会导致ApplicationContext上的消息循环终止。
手动创建一个类:产生三个窗口,只有把三个窗口全部关闭程序才终止运行(基于第三种Run方法)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
//从ApplicationContext派生一个类出来,
public class MyApplication : ApplicationContext
{
static int WindowsCount;//用于记录窗口个数
private Form Windows1, Windows2, Windows3;//申请三个Form窗口 private只限于本类成员访问
//构造函数,分别实例化三个窗口
public MyApplication()
{
WindowsCount = 0;
/*实例化Windows1*/
Windows1 = new Form();
Windows1.Text = "窗口1";
Windows1.Size = new System.Drawing.Size(300, 300);
Windows1.Location = new System.Drawing.Point(50, 100);
Windows1.Name = "Form1";
Windows1.FormClosed += OnMainFormClosed;//处理事件(窗口关闭的处理事件)
WindowsCount += 1;//窗口总数加一
Windows2 = new Form();
Windows2.Text = "窗口2";
Windows2.Size = new System.Drawing.Size(300, 300);
Windows2.Location = new System.Drawing.Point(50, 100);
Windows2.Name = "Form2";
Windows2.FormClosed += OnMainFormClosed;//处理事件(窗口关闭的处理事件)
WindowsCount += 1;//窗口总数加一
Windows3 = new Form();
Windows3.Text = "窗口3";
Windows3.Size = new System.Drawing.Size(300, 300);
Windows3.Location = new System.Drawing.Point(50, 100);
Windows3.Name = "Form3";
Windows3.FormClosed += OnMainFormClosed;//处理事件(窗口关闭的处理事件)
WindowsCount += 1;//窗口总数加一
//显示3个窗口
Windows1.Show();
Windows2.Show();
Windows3.Show();
}
private void OnMainFormClosed(object sender,FormClosedEventArgs e)
{
WindowsCount -= 1;
if (WindowsCount == 0)
ExitThread();//调用ExitThead终止消息循环
}
}
namespace application1
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyApplication());
}
}
}
下面的代码示例显示两个窗体,并在两个窗体都关闭时退出应用程序。在应用程序启动和退出时,它会记住每个窗体的位置。此示例演示如何使用 ApplicationContext 和 Application.Run(context) 方法在启动应用程序时显示多个窗体。
类 MyApplicationContext 从 ApplicationContext 继承,并跟踪每个窗体关闭的时间,然后在这两个窗体均关闭时退出当前线程。该类为用户存储每个窗体的位置。窗体位置数据存储在标题为 Appdata.txt 的文件中,该文件在 UserAppDataPath 确定的位置中创建。
给定 ApplicationContext 的情况下,Main 方法调用 Application.Run(context) 启动应用程序。
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Text;
using System.IO;
namespace ScreenSplit
{
static class Program
{
// 初始化窗体1大小及标题文本
public class AppForm1 : System.Windows.Forms.Form
{
public AppForm1()
{
Screen screen = Screen.FromRectangle(new Rectangle(0, 0, 0, 0));
this.Size = new System.Drawing.Size(screen.WorkingArea.Width / 2, screen.WorkingArea.Height);
this.Text = "AppForm1";
}
}
// 初始化窗体2大小及标题文本
public class AppForm2 : System.Windows.Forms.Form
{
public AppForm2()
{
Screen screen = Screen.FromRectangle(new Rectangle(0, 0, 0, 0));
this.Size = new System.Drawing.Size(screen.WorkingArea.Width / 2, screen.WorkingArea.Height);
this.Text = "AppForm2";
}
}
// 利用ApplicationContext类处理程序的启动、关闭
class MyApplicationContext : ApplicationContext
{
private int formCount;
private AppForm1 form1;
private AppForm2 form2;
private Rectangle form1Position;
private Rectangle form2Position;
private FileStream userData;
private MyApplicationContext()
{
formCount = 0;
// 应用程序退出
Application.ApplicationExit += new EventHandler(this.OnApplicationExit);
try
{
// 在用户目录使用appdata.txt文件保存窗体退出时的位置与大小
userData = new FileStream(Application.UserAppDataPath + "//appdata.txt", FileMode.OpenOrCreate);
}
catch (IOException e)
{
// 程序退出时异常处理.
MessageBox.Show("An error occurred while attempting to show the application." +
"The error is:" + e.ToString());
// 退出当前主线程
ExitThread();
}
//窗体关闭
form1 = new AppForm1();
form1.Closed += new EventHandler(OnFormClosed);
form1.Closing += new CancelEventHandler(OnFormClosing);
formCount++;
form2 = new AppForm2();
form2.Closed += new EventHandler(OnFormClosed);
form2.Closing += new CancelEventHandler(OnFormClosing);
formCount++;
// 从文件中读取保存窗体位置与大小的参数
if (ReadFormDataFromFile())
{
Screen screen = Screen.FromRectangle(new Rectangle(0, 0, 0, 0));
form1.Top = 0; form1.Left = 0;
form2.Top = 0; form2.Left = screen.WorkingArea.Width / 2;
form1.StartPosition = FormStartPosition.Manual;
form2.StartPosition = FormStartPosition.Manual;
form1.Bounds = form1Position;
form2.Bounds = form2Position;
}
// 显示双窗体
form1.Show();
form2.Show();
}
private void OnApplicationExit(object sender, EventArgs e)
{
// 保存窗体位置与大小
WriteFormDataToFile();
try
{
// 忽略窗体关闭时可能出现的错误
userData.Close();
}
catch { }
}
private void OnFormClosing(object sender, CancelEventArgs e)
{
// 保存窗体位置与大小
if (sender is AppForm1)
form1Position = ((Form)sender).Bounds;
else if (sender is AppForm2)
form2Position = ((Form)sender).Bounds;
}
private void OnFormClosed(object sender, EventArgs e)
{
// 关闭所有窗体,退出主线程
formCount--;
if (formCount == 0)
{
ExitThread();
}
}
private bool WriteFormDataToFile()
{
// 保存窗体位置与大小到用户文件
UTF8Encoding encoding = new UTF8Encoding();
RectangleConverter rectConv = new RectangleConverter();
String form1pos = rectConv.ConvertToString(form1Position);
String form2pos = rectConv.ConvertToString(form2Position);
byte[] dataToWrite = encoding.GetBytes("~" + form1pos + "~" + form2pos);
try
{
userData.Seek(0, SeekOrigin.Begin);
userData.Write(dataToWrite, 0, dataToWrite.Length);
userData.Flush();
userData.SetLength(dataToWrite.Length);
return true;
}
catch
{
return false;
}
}
private bool ReadFormDataFromFile()
{
// 从文件中读取窗体大小与位置
UTF8Encoding encoding = new UTF8Encoding();
String data;
if (userData.Length != 0)
{
byte[] dataToRead = new Byte[userData.Length];
try
{
userData.Seek(0, SeekOrigin.Begin);
userData.Read(dataToRead, 0, dataToRead.Length);
}
catch (IOException e)
{
String errorInfo = e.ToString();
return false;
}
data = encoding.GetString(dataToRead);
try
{
// 转换数据文件为 rectangles
RectangleConverter rectConv = new RectangleConverter();
String form1pos = data.Substring(1, data.IndexOf("~", 1) - 1);
form1Position = (Rectangle)rectConv.ConvertFromString(form1pos);
String form2pos = data.Substring(data.IndexOf("~", 1) + 1);
form2Position = (Rectangle)rectConv.ConvertFromString(form2pos);
return true;
}
catch
{
return false;
}
}
else
{
// 无数据文件时,缺省窗体位置与大小
return false;
}
}
[STAThread]
static void Main(string[] args)
{
MyApplicationContext context = new MyApplicationContext();
Application.Run(context);
}
}
}
}
//以上代码保存成Program.cs,修改form名称后可以直接使用。源自MSDN,稍作修改