簡體   English   中英

最后一張表格關閉后如何關閉申請?

[英]How do I close application after close of the last form?

我正在使用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. 顯示啟動畫面
  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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM