【问题标题】:How do I close application after close of the last form?关闭最后一个表格后如何关闭申请?
【发布时间】:2019-11-23 19:15:23
【问题描述】:

我正在使用 C#。我在 Program.Main 中启动。这将打开 frmSplash。 frmSplash 执行初始化(错误收集/数据库连接等)的全部负载,然后打开 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 已经加载并且可见。

【问题讨论】:

  • 尝试调用 Visibile 属性而不是 this.Close 或 this.Hide 并检查它是否有效。所以基本上它是这样的:frmSplash.Visible=false; // 其中 frmSplash 是您希望隐藏的启动画面。
  • @Rohan - 好吧,行为不会因此而改变,我并不感到惊讶。将 frmSplash 的 visible 属性设置为 false 不会卸载表单。我想卸载 frmSplash 并让 frmGeneric 加载。但是,调用 frmSplashClose() 会关闭应用程序。

标签: c# .net winforms


【解决方案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();
    }
}

【讨论】:

  • 非常感谢 - 非常感谢您的努力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
相关资源
最近更新 更多