Show Splash Screen during Loading the Main Form

拈花ヽ惹草 提交于 2019-11-27 05:13:41

There are different way of creating splash screens. It's better to separate the logic of showing and closing splash screen from logic of your main form.

To do so, you can create a LoadCompleted event and then subscribe for it in Program class, and show and close your splash screen there.

Here is an implementation of what I described above:

1- In your MainForm, add a LoadCompleted event and then override OnLoad method to raise the event. (Probably Shown event is applicable instead of our custom event.)

public event EventHandler LoadCompleted;
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    this.OnLoadCompleted(EventArgs.Empty);
}
protected virtual void OnLoadCompleted(EventArgs e)
{
    var handler = LoadCompleted;
    if (handler != null)
        handler(this, e);
}
private void MainForm_Load(object sender, EventArgs e)
{
    //Just for test, you can make a delay to simulate a time-consuming task
    //In a real application here you load your data and other settings
}

2- In the Program class, show SplashForm then subscribe for LoadCompleted event of your MainForm and show MainForm, then in LoadCompleted, close SplashForm.

static class Program
{
    static SplashForm mySplashForm;
    static MainForm myMainForm;
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        //Show Splash Form
        mySplashForm = new SplashForm();
        if (mySplashForm != null)
        {
            Thread splashThread = new Thread(new ThreadStart(
                () => { Application.Run(mySplashForm); }));
            splashThread.SetApartmentState(ApartmentState.STA);
            splashThread.Start();
        }
        //Create and Show Main Form
        myMainForm = new MainForm();
        myMainForm.LoadCompleted += MainForm_LoadCompleted;
        Application.Run(myMainForm);
        if(!(mySplashForm == null || mySplashForm.Disposing || mySplashForm.IsDisposed))
            mySplashForm.Invoke(new Action(() => { 
                mySplashForm.TopMost = true; 
                mySplashForm.Activate(); 
                mySplashForm.TopMost = false; }));
    }
    private static void MainForm_LoadCompleted(object sender, EventArgs e)
    {
        if (mySplashForm == null || mySplashForm.Disposing || mySplashForm.IsDisposed)
            return;
        mySplashForm.Invoke(new Action(() => { mySplashForm.Close(); }));
        mySplashForm.Dispose();
        mySplashForm = null;
        myMainForm.TopMost = true; 
        myMainForm.Activate(); 
        myMainForm.TopMost = false;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!