.NET Splash屏幕问题

COD*_*ODe 3 .net c# splash-screen

我有一个通过Shown事件调用的C#数据库应用程序的启动画面.启动屏幕包含一些在调用主窗体的构造函数时预处理的信息,因此我使用了Shown事件,因为该信息应该可用.

但是,当显示启动画面时,主窗体会变白,菜单栏,底部菜单栏,甚至灰色背景都是白色和不可见的.看起来程序正在挂起,但是在我内置的5秒延迟之后,横幅消失了,程序正常显示.此外,在横幅上,我有标签,当启动画面显示时不显示...

这是我的代码,为什么它不起作用背后的一些推理会有很大帮助.

SPLASH屏幕代码:

public partial class StartupBanner : Form
{
    public StartupBanner(int missingNum, int expiredNum)
    {
        InitializeComponent();
        missingLabel.Text = missingNum.ToString() + " MISSING POLICIES";
        expiredLabel.Text = expiredNum.ToString() + " EXPIRED POLICIES";
    }
}
Run Code Online (Sandbox Code Playgroud)

来电代码:

    private void MainForm_Shown(object sender, EventArgs e)
    {
        StartupBanner startup = new StartupBanner(missingPoliciesNum, expiredPoliciesNum);
        startup.MdiParent = this;
        startup.Show();

        Thread.Sleep(5000);
        startup.Close();
    }
Run Code Online (Sandbox Code Playgroud)

使用startup.ShowDialog()在启动屏幕上显示正确的标签信息,但这会锁定应用程序,并且我需要在大约5秒后消失,这就是为什么它会引起轰动.;)

小智 6

首先使用ShowDialog()而不是Show()运行启动画面,因此启动画面锁定主窗体并且不锁定主线程:

private void MainForm_Shown(object sender, EventArgs e)
{
    StartupBanner startup = new StartupBanner(missingPoliciesNum, expiredPoliciesNum);
    startup.ShowDialog();
}
Run Code Online (Sandbox Code Playgroud)

在启动屏幕窗体中,您应该定义一个在5秒后关闭窗体的计时器:

public partial class StartupBanner : Form
{
    private System.Windows.Forms.Timer _closeTimer = new Timer();

    public StartupBanner(int missingNum, int expiredNum)
    {
        this.InitializeComponent();
        missingLabel.Text = missingNum.ToString() + " MISSING POLICIES";
        expiredLabel.Text = expiredNum.ToString() + " EXPIRED POLICIES";

        this._closeTimer = new System.Windows.Forms.Timer();
        this._closeTimer.Interval = 5000;
        this._closeTimer.Tick += new EventHandler(this._closeTimer_Tick);
        this._closeTimer.Start();
    }

    private void _closeTimer_Tick(object sender, EventArgs e)
    {
        System.Windows.Forms.Timer timer = (System.Windows.Forms.Timer)sender;
        timer.Stop();

        this.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:Thread.Sleep()锁定整个线程,例如表单的每个动作,以便它们无法处理任何消息,如点击或按下按钮.它们不在后台运行,因此最好使用可以在后台关闭表单的计时器.

FIX:删除startup.MdiParent = this; 线