Click here to Skip to main content
15,355,659 members
Articles / Programming Languages / C#
Article
Posted 12 Jul 2006

Stats

114.4K views
3.9K downloads
121 bookmarked

Use a splash screen in your application

Rate me:
Please Sign up or sign in to vote.
4.72/5 (34 votes)
12 Jul 2006CPOL2 min read
This article will show you how to display a splash screen during application initialization using C# in VS2005

Sample Image - usesplashscreen.jpg

Introduction

This article will show you how to display a splash screen during application initialization using C# in VS2005 IDE.

Background

Sometimes, we have to put a lot of initialization code into the MainForm's OnLoad() override. Due to this, when the application starts up, it looks like a mess: The main application form just doesn't pop up nicely and ready to be used. Now we need to create a splash screen, let's begin.

Preparations

  1. Create a Windows Forms project Named SplashScreen
  2. Delete Form1.cs
  3. Add a new Form named frmMain

1. Creating the Core Code

Firstly, create an interface called ISplashForm, which includes a method named SetStatusInfo in order to display the loading status on the splash screen. Once done, the interface should look like this:

C#
public interface ISplashForm
{
    void SetStatusInfo(string NewStatusInfo);
}

Secondly, create a class called Splasher, where static members Show, Close and the Status writeonly property can be used as their names suggest to show and close the Splash Screen as well as to update the loading status displayed on the SplashForm. Here is what the implementation of the class looks like:

C#
using System;
using System.Windows.Forms;
using System.Threading;
using System.Reflection;

    public class Splasher
    {
        private static Form m_SplashForm = null;
        private static ISplashForm m_SplashInterface = null;
        private static Thread m_SplashThread = null;
        private static string m_TempStatus = string.Empty;

        /// <summary>
        /// Show the SplashForm
        /// </summary>
        public static void Show(Type splashFormType)
        {
            if (m_SplashThread != null)
                return;
            if (splashFormType == null)
            {
                throw (new Exception("splashFormType is null"));
            }

            m_SplashThread = new Thread(new ThreadStart(delegate()
            {
                CreateInstance(splashFormType);
                Application.Run(m_SplashForm);
            }));

            m_SplashThread.IsBackground = true;
            m_SplashThread.SetApartmentState(ApartmentState.STA);
            m_SplashThread.Start();
        }

        /// <summary>
        /// set the loading Status
        /// </summary>
        public static string Status
        {
            set
            {
                if (m_SplashInterface == null || m_SplashForm == null)
                {
                    m_TempStatus = value;
                    return;
                }
                m_SplashForm.Invoke(
                        new SplashStatusChangedHandle(delegate(string str)
                { m_SplashInterface.SetStatusInfo(str); }),
                        new object[] { value }
                    );
            }

        }

        /// <summary>
        /// Close the SplashForm
        /// </summary>
        public static void Close()
        {
            if (m_SplashThread == null || m_SplashForm == null) return;

            try
            {
                m_SplashForm.Invoke(new MethodInvoker(m_SplashForm.Close));
            }
            catch (Exception)
            {
            }
            m_SplashThread = null;
            m_SplashForm = null;
        }

        private static void CreateInstance(Type FormType)
        {

            object obj = FormType.InvokeMember(null,
                                BindingFlags.DeclaredOnly |
                                BindingFlags.Public |
                BindingFlags.NonPublic |
                                BindingFlags.Instance |
                BindingFlags.CreateInstance, null, null, null);
            m_SplashForm = obj as Form;
            m_SplashInterface = obj as ISplashForm;
            if (m_SplashForm == null)
            {
                throw (new Exception("Splash Screen must inherit from
                        System.Windows.Forms.Form"));
            }
            if (m_SplashInterface == null)
            {
                throw (new Exception("must implement interface ISplashForm"));
            }

            if (!string.IsNullOrEmpty(m_TempStatus))
                m_SplashInterface.SetStatusInfo(m_TempStatus);
        }

        private delegate void SplashStatusChangedHandle(string NewStatusInfo);
    }

2. Creating the Splash Screen

Just create a new Windows Form named frmSplash. The form should be centered on the screen (StartPosition), be topmost (TopMost) and shouldn't have a border (FormBorderStyle), set the BackgroundImage property to your splash image and set the form size equal to the image size. In order to display the loading status on the form, we need to place a label on the form and then implement ISplashForm. If the label is called lbStatusInfo, the ISplashForm implementation should look like this:

C#
void ISplashForm.SetStatusInfo(string NewStatusInfo)
{
   lbStatusInfo.Text = NewStatusInfo;
}

3. Modifying the MainForm's code

Now we need to make some modifications to the frmMain class. Once done, the constructed function should look somewhat like this:

C#
public frmMain()
{

    Splasher.Status = "Creating MainForm...";
    System.Threading.Thread.Sleep(1000);

    InitializeComponent();

    Splasher.Status = "Loading Files...";
    System.Threading.Thread.Sleep(1500);

    Splasher.Status = "Loading Plug/Ins...";
    System.Threading.Thread.Sleep(1500);

     Splasher.Status = "Sleeping 1 second...";
     System.Threading.Thread.Sleep(1000);

     Splasher.Close();
}

4. Modifying the Entry Point function

In order to use Splash Screen, we have to modify our entry point function appropriately:

C#
[STAThread]
static void Main()
{
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Splasher.Show(typeof(frmSplash));
      frmMain MyMainForm = new frmMain();
      Application.Run(MyMainForm);
}

That's all about it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

cncxz
China China
No Biography provided

Comments and Discussions

 
GeneralAppreciate your work!! Pin
Li Shu23-Jan-10 1:07
MemberLi Shu23-Jan-10 1:07 
GeneralQuite useful Pin
Member 26446007-Mar-09 8:12
MemberMember 26446007-Mar-09 8:12 
GeneralBug Pin
Simon P Stevens18-Jun-08 23:19
MemberSimon P Stevens18-Jun-08 23:19 
Generalproblem with ApartmentState.STA Pin
Ossan Dust20-May-08 23:24
MemberOssan Dust20-May-08 23:24 
Newsuse Opacity attribute when m_SplashForm is closing Pin
wangkuang55-Mar-08 4:53
Memberwangkuang55-Mar-08 4:53 
GeneralExcellent work! Pin
Alan Yost30-Nov-07 10:25
MemberAlan Yost30-Nov-07 10:25 
GeneralBug [modified] Pin
tranbagu25-Oct-07 21:21
Membertranbagu25-Oct-07 21:21 
GeneralRe: Bug -> solution Pin
chr.dev16-Nov-07 2:25
Memberchr.dev16-Nov-07 2:25 
GeneralRe: Bug -&gt; solution Pin
wangkuang57-Mar-08 3:45
Memberwangkuang57-Mar-08 3:45 
Generalnice! Pin
radioman.lt6-Aug-07 21:49
Memberradioman.lt6-Aug-07 21:49 
GeneralREALLY GREAT ! Pin
lucatoldo18-Jun-07 1:27
Memberlucatoldo18-Jun-07 1:27 
GeneralAdd new operation during the splash Pin
ayeleteric10-Jun-07 19:44
Memberayeleteric10-Jun-07 19:44 
GeneralGreat example! Pin
DVroegop13-Apr-07 3:53
MemberDVroegop13-Apr-07 3:53 
GeneralThanks Pin
Raj Bashetty20-Mar-07 11:03
MemberRaj Bashetty20-Mar-07 11:03 
GeneralAdding more "static" labels. Pin
CMercs14-Feb-07 5:55
MemberCMercs14-Feb-07 5:55 
Generalvb.net version Pin
Greg Hazz7-Nov-06 10:17
MemberGreg Hazz7-Nov-06 10:17 
GeneralRe: vb.net version Pin
Greg Hazz9-Nov-06 10:37
MemberGreg Hazz9-Nov-06 10:37 
GeneralRe: vb.net version Pin
cncxz4-Feb-07 21:35
Membercncxz4-Feb-07 21:35 
QuestionTopMost property Pin
marutj2-Oct-06 16:09
Membermarutj2-Oct-06 16:09 
GeneralfrmMain does not appear in the Foreground Pin
Zupcoder9-Sep-06 13:17
MemberZupcoder9-Sep-06 13:17 
GeneralRe: frmMain does not appear in the Foreground Pin
Allad11-Jan-07 20:33
MemberAllad11-Jan-07 20:33 
Questionthe splash won't disappear Pin
Huisheng Chen13-Aug-06 21:38
MemberHuisheng Chen13-Aug-06 21:38 
QuestionVB version of this code? Pin
Joshua Ng18-Jul-06 22:30
MemberJoshua Ng18-Jul-06 22:30 
AnswerRe: VB version of this code? [modified] Pin
cncxz18-Jul-06 23:53
Membercncxz18-Jul-06 23:53 
GeneralRe: VB version of this code? Pin
Joshua Ng19-Jul-06 20:22
MemberJoshua Ng19-Jul-06 20:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.