防止关闭启动窗体后应用程序退出的解决方案

1、首先新建一个类MyAppContext,继承自System.Windows.Forms.ApplicationContext类:

public class MyApplicationContext : ApplicationContext
{
public MyApplicationContext()
{
//启动登录窗口
LoginForm startForm = new LoginForm();
startForm.Show();
}
}

2、然后在Program.cs文件中修改成如下代码:

static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

//调用Application.Run(ApplicationContext context)重载函数来启动窗口
Application.Run(new MyApplicationContext());
}
}

3、然后在项目里面新建一个名为BaseForm的基窗体:

public class BaseForm : Form
{
public BaseForm()
{
//给所有继承自BaseForm的窗口注册FormClosed事件,
//只有当前应用程序的所有窗口都关闭之后才退出应用程序
this.FormClosed += (sender, e) =>
{
if (Application.OpenForms.Count == 0)
{
Application.Exit();
}
};
}
}

4、然后新建其它窗体,并继承自BaseForm