C#winforms启动(Splash)表单没有隐藏

TK.*_*TK. 9 c# show-hide winforms

我有一个winforms应用程序,我在其中使用2个表单来显示所有必要的控件.第一个表单是一个启动画面,它告诉用户它正在加载等等.所以我使用以下代码:

Application.Run( new SplashForm() );
Run Code Online (Sandbox Code Playgroud)

一旦应用程序完成加载,我希望SplashForm隐藏或我发送到后面和主要显示.我目前正在使用以下内容:

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

    // Show the GUI
    mainForm.Show();
    mainForm.BringToFront();
}
Run Code Online (Sandbox Code Playgroud)

我所看到的是显示了MainForm,但SplashForm仍然可以在"顶部"显示.我目前正在做的是点击MainForm手动将它带到前面.有关为什么会发生这种情况的任何想法?

Grz*_*nio 21

可能你只想关闭飞溅形式,而不是发送回来.

我在一个单独的线程上运行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;
    }
...
}
Run Code Online (Sandbox Code Playgroud)

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

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


小智 5

这对于防止您的启动屏幕在关闭后阻止您的焦点并将主窗体推送到后台至关重要:

protected override bool ShowWithoutActivation {
    get { return true; }
}
Run Code Online (Sandbox Code Playgroud)

将此添加到您的splash表单类.