关闭最后一份表格后如何关闭申请?



我正在使用C#。我正在Program.Main中启动。这将打开 frmSplash。frmSplash 执行整个初始化加载(Errs 集合/数据库连接等(,然后打开 frmGeneric。frmGeneric 从数据库加载一堆信息,并使用数据库中定义的控件填充自身。它可能会打开 frmGeneric 的其他实例。事实上,它可能会在其他实例关闭之前自行关闭。

初始化过程在 frmSplash 中发生,一旦它可见,当用户单击"继续"按钮时。目前,一旦显示 frmGeneric 的第一个实例,我在 frmSplash 中调用this.Hide(),但我实际上希望 frmSplash 卸载。

如果我在 frmSplash 中调用this.Close(),即使在显示 frmGeneric 之后,整个应用程序也会关闭。

显然,最后一个要关闭的 frmGeneric 不会知道它是最后一个(它是通用的(。如何在初始化后关闭 frmSplash,而不退出应用程序?

private void cmdContinue_Click(object sender, EventArgs e)
{
    Globals oG = null;
    App oApp = null;
    frmGeneric oForm = null;
    try
    {
        txtStatus.Text = "Initialising Globals object...";
        oG = new Globals();
        // some other stuff redacted 
        txtStatus.Text = "Showing startup form...";
        oForm = new frmGeneric();
        oForm.Globals = oG;
        if (!oForm.RunForm() throw new Exception("Could not run form");
        // enough of me
        this.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        Application.Exit();
    }
}

在此。Close(( 在上面的代码中,整个应用程序关闭,即使 oForm 已加载并且可见。

问题有两点:

  1. 显示初始屏幕
  2. 关闭
  3. 最后一个窗体(不是主窗体(后关闭应用程序。

对于这两个要求,您可以依赖 Microsoft.VisualBasic.dll 中存在的WindowsFormsApplicationBase

  • 它允许您指定要在应用程序启动时显示的初始屏幕。
  • 它还允许您指定在关闭主窗体后关闭应用程序或在关闭所有窗体后关闭应用程序shutdown style

using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(true);
        var app = new MyApplication();
        app.Run(Environment.GetCommandLineArgs());
    }
}
public class MyApplication : WindowsFormsApplicationBase
{
    public MyApplication()
    {
        this.ShutdownStyle = ShutdownMode.AfterAllFormsClose;
    }
    protected override void OnCreateMainForm()
    {
        MainForm = new YourMainForm();
    }
    protected override void OnCreateSplashScreen()
    {
        SplashScreen = new YourSplashForm();
    }
}

最新更新