我有两个表格...当我启动应用程序并使用标题栏的关闭“X”时,整个应用程序都会关闭...现在,当我从第一个表格中选择一个选项,在我的情况下,它是一个名为“ADD”的按钮,因为它是电话簿应用程序...它转到第二个表格,因为我使用了1stform.hide()和2ndform.show()...现在,当我从标题栏中的“X”进行操作时,它不会完全关闭,因为第一个表格没有关闭...如何编程以使任何阶段整个应用程序都应该关闭。
Application.Exit
。这将关闭所有当前打开的表单并立即退出应用程序。正如我刚才说的,我不太推荐这种方法,因为从每个表单的FormClosed
事件处理程序中调用Application.Exit
表明你的设计出了严重问题。
如果单一启动窗体的范式不适合您,您应该考虑自己动手并自定义Program.cs
源文件中的Main
方法。请参阅这个相关问题中给出的答案,了解如何实现。
FormClosed
事件。该文档可在此处找到,但它只是由 Form
类公开的普通事件。您可以像订阅应用程序中的任何其他事件一样订阅它(例如 Button.Click
)。 - Cody GrayFormClosing
事件,并添加以下代码:Application.Exit();
这将停止整个应用程序,并关闭所有窗口。但是,如果有一个后台线程正在运行,进程本身将存活。在这种情况下,您可以使用:
Environment.Exit();
private void Form_ClosingEventhandler()(object sender, CancelEventArgs e)
{
//Perform any processing if required like saving user settings or cleaning resources
Application.Exit();
}
//Where you create new form and show it.
Form1 frm= new Form1();
//set other properties
frm.Closing += new EventHandler(Form_ClosingEventhandler);
Form2 frm2= new Form2();
//set other properties
frm2.Closing += new EventHandler(Form_ClosingEventhandler);
当用户添加电话号码后,您肯定不希望关闭整个应用程序吧?您只需要确保您的主窗口再次变得可见即可。请按以下方式编写:
private void AddButton_Click(object sender, EventArgs e) {
var frm = new AddPhoneNumber();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = this.Location;
frm.Size = this.Size; // optional
frm.FormClosing += delegate { this.Show(); };
frm.Show();
this.Hide();
}