簡體   English   中英

C#winforms啟動(Splash)表單沒有隱藏

[英]C# winforms startup (Splash) form not hiding

我有一個winforms應用程序,我在其中使用2個表單來顯示所有必要的控件。 第一個表單是一個啟動畫面,它告訴用戶它正在加載等等。所以我使用以下代碼:

Application.Run( new SplashForm() );

一旦應用程序完成加載,我希望SplashForm隱藏或我發送到后面和主要顯示。 我目前正在使用以下內容:

private void showMainForm()
{
    this.Hide();
    this.SendToBack();

    // Show the GUI
    mainForm.Show();
    mainForm.BringToFront();
}

我所看到的是顯示了MainForm,但SplashForm仍然可以在“頂部”顯示。 我目前正在做的是點擊MainForm手動將它帶到前面。 有關為什么會發生這種情況的任何想法?

可能你只想關閉飛濺形式,而不是發送回來。

我在一個單獨的線程上運行splash表單(這是SplashForm類):

class SplashForm
{
    //Delegate for cross thread call to close
    private delegate void CloseDelegate();

    //The type of form to be displayed as the splash screen.
    private static SplashForm splashForm;

    static public void ShowSplashScreen()
    {
        // Make sure it is only launched once.

        if (splashForm != null)
            return;
        Thread thread = new Thread(new ThreadStart(SplashForm.ShowForm));
        thread.IsBackground = true;
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();           
    }

    static private void ShowForm()
    {
        splashForm = new SplashForm();
        Application.Run(splashForm);
    }

    static public void CloseForm()
    {
        splashForm.Invoke(new CloseDelegate(SplashForm.CloseFormInternal));
    }

    static private void CloseFormInternal()
    {
        splashForm.Close();
        splashForm = null;
    }
...
}

並且主程序功能如下所示:

[STAThread]
static void Main(string[] args)
{
    SplashForm.ShowSplashScreen();
    MainForm mainForm = new MainForm(); //this takes ages
    SplashForm.CloseForm();
    Application.Run(mainForm);
}

這對於防止您的啟動屏幕在關閉后阻止您的焦點並將主窗體推送到后台至關重要:

protected override bool ShowWithoutActivation {
    get { return true; }
}

將此添加到您的splash表單類。

如果我理解正確,您應該只在主窗體上使用Application.Run。 因此,要么首先使用以下內容顯示您的啟動:

using(MySplash form = new MySplash())
   form.ShowDialog();

然后隨時在MySplash中手動關閉它。

或者在主窗體中顯示它加載事件處理程序,然后等待它關閉或其他任何東西,直到你讓Load方法完成。 (可能在顯示之前將Visible設置為false,然后再返回true。

我相信這可能是我目前設計中的一個設計缺陷!

我認為實現我需要的最好方法是讓所有東西都能從MainForm中控制出來。 所以我可以用:

Application.Run(new MainForm());

然后,這將負責顯示/更新/隱藏SplashScreen。 通過這種方式,我可以與MainForm管理的系統的其余部分進行必要的復雜操作。

暫無
暫無

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

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