下面的代码示例显示两个窗体,并在两个窗体都关闭时退出应用程序。在应用程序启动和退出时,它会记住每个窗体的位置。此示例演示如何使用 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.OnApplicationEx