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

时间:2019-11-23 08:43:09

标签: c# .net winforms

我正在使用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();
    }
}

在上述代码中的this.Close()处,即使oForm已加载并且可见,整个应用程序也会关闭。

1 个答案:

答案 0 :(得分:1)

问题有两点:

  1. 显示启动画面
  2. 关闭最后一个表单(不是主表单)后关闭应用程序。

对于这两个要求,您都可以依靠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();
    }
}
相关问题