如果应用程序有两个以上的表单而没有多次显示消息框,如何关闭整个应用程序

我正在使用Windows窗体开发应用程序。 该项目包含3个表单:一个登录表单是主表单,另外两个表单是登录表单的子表单。

我的问题是想要通过在表单关闭事件中使用Application.Exit()关闭整个应用程序,我的消息框不止一次显示对话框。

1.此代码以登录forms即主要forms:

 private void FrmLogIn_FormClosing(object sender, FormClosingEventArgs e) { DialogResult loginResult = MessageBox.Show("Do you want to close this application?","Close",MessageBoxButtons.YesNo,MessageBoxIcon.Warning); if (loginResult == DialogResult.Yes) { Application.Exit(); } } 

2.AdminForm关闭事件是登录表格的子表格:

  private void FrmAdmin_FormClosing(object sender, FormClosingEventArgs e) { DialogResult loginResult = MessageBox.Show("Do you want to close this application?","Close",MessageBoxButtons.YesNo,MessageBoxIcon.Warning); if (loginResult == DialogResult.Yes) { Application.Exit(); } } 

3.Billoperations形成关闭事件,即登录表格的子表格:

 private void FrmBillOperation_FormClosing(object sender, FormClosingEventArgs e) { DialogResult loginResult = MessageBox.Show("Do you want to close this application?","Close",MessageBoxButtons.YesNo,MessageBoxIcon.Warning); if (loginResult == DialogResult.Yes) { Application.Exit(); } } 

当我单击任何forms的关闭按钮时,它将只显示一次MessageBox消息。 请帮我。

使所有FormClosing方法调用ApplicationShutdown函数,该函数在中心位置处理此问题。 您不希望将此代码复制到您创建的每个新表单。

在此方法中,您可以检查一个名为IsShuttingDown的布尔值(监视线程安全性)。 如果已经存在,请保留该方法,否则您会提出问题并开始退出。

传递给FormClosing事件的FormClosingEventArgs实例有一个CloseReason属性,当调用Application类的Exit方法时,该属性将设置为CloseReason.ApplicationExit :您的处理程序应检查此条件,如果是,则不采取进一步操作。

 private void FrmLogIn_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.ApplicationExit) return; ... } 

您可以尝试使用此代码

 FormCollection fc = Application.OpenForms; if (fc!= null && fc.Count > 0) { for (int i = 1; i < fc.Count; i++) { if (fc!= null && fc.IsDisposed!= true) { fc.Dispose(); } } } 
 private void sh_interface_FormClosing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("This will close down the whole application. Confirm?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes) { foreach (Form f in Application.OpenForms) { if (!f.IsDisposed) f.Dispose(); } } else { e.Cancel = true; this.Activate(); } } 

这将关闭所有表单,包括隐藏表单和Application.Run(new something())中的主表单…此方法也适用于在模板类Form Closing事件中编码时在inheritance类中调用。