如何管理C#多表单应用程序

问题描述 投票:0回答:1

我有一个 C# 多表单应用程序。我有一个 toolStripMenu,允许用户在应用程序中的不同表单之间导航。在表单之间切换时,我关闭当前表单,然后打开新表单。在某些表单上,如果用户尚未保存更改,则会有一个消息框确认用户想要退出而不保存。如果他们选择“否”,退出事件将被取消。

我打开新表单的方法会检查以确保当前表单在打开新表单之前已关闭,以防用户取消退出事件。

我的问题是关闭应用程序。我无法使用 Form_Closed Event 中的典型方法:

if(Application.OpenForms.Count == 0) 
  Application.Exit

因为我在打开新表单之前关闭了当前表单;这意味着当当前表单关闭时,

Application.OpenForms.Count
始终为0;但如果没有这种方法,当所有表单关闭时,我的应用程序永远不会退出。

讨论的另一种模式是有一个“主窗体”......但这确实不适合我对此应用程序的需求。我不知道该怎么办

c# winforms
1个回答
0
投票

不要仅仅依赖

Application.OpenForms.Count
。相反,维护一个指示应用程序是否应退出的标志。当用户在任何表单上确认退出时,将此标志设置为 true

private bool shouldExit = false; // Flag to track whether the application should exit


protected override void OnFormClosing(FormClosingEventArgs e) // Override OnFormClosing event in your forms
{
    if (!shouldExit)
    {
        
        if (unsavedChangesExist) // Check for unsaved changes and prompt user if necessary
        {
            DialogResult result = MessageBox.Show("There are unsaved changes. Are you sure you want to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result == DialogResult.No)
            {
                e.Cancel = true; // Cancel the close operation
                return;
            }
        }
    }

    base.OnFormClosing(e);
}


private void ExitApplication() //This will be your Centralized exit logic
{
    foreach (Form form in Application.OpenForms)
    {
        
        if (form is YourFormType yourForm && yourForm.UnsavedChangesExist) // Check for unsaved changes on each form
        {
            DialogResult result = MessageBox.Show("There are unsaved changes on one or more forms. Are you sure you want to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result == DialogResult.No)
            {
                return; // Don't exit the application stay back in the same application.
            }
        }
    }

    Application.Exit(); // Exit the application
}


private void exitToolStripMenuItem_Click(object sender, EventArgs e) // Menu item click event for exiting the application
{
    shouldExit = true;
    ExitApplication();
}
© www.soinside.com 2019 - 2024. All rights reserved.