[英]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已加載並且可見,整個應用程序也會關閉。
問題有兩點:
對於這兩個要求,您都可以依賴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.