C#建立啟動畫面

來源:互聯網
上載者:User

文章來源:http://www.codeproject.com/Articles/3542/How-to-do-Application-Initialization-while-showing?rp=/KB/cs/AppLoadingArticle/AppLoading1.zip

  • Version A (Quick 'n Dirty): Download demo project - 32 Kb
  • Version B (MultiThreaded): Download demo project - 32 Kb

Update 28.01.03

This article has been updated with Chris Austin's suggestion (Thanks Chris!
And thanks to Phil Bolduc for the fix on Chris' stuff ;)) and an alternative (multithreaded) approach has been added, based on Jabes idea
(Thanks Jabes!).

Introduction

This articles shows how to display a splash screen during your application initialization. This article assumes that you familiar with C# and the VS.NET IDE.

Background

I had put the lot of my initialization code into the main forms OnLoad() override. The code parsed
configuration files, created control and the such. When my application started up, it looked like a mess: The main application form just didn't pop up nicely and ready to be used. I decided to create a Splash Screen, which should pop up right after starting
the executable. While the splash screen was shown, I wanted to do my initialization and once that was done, I'd hide the splash screen and show the main application window. This article contains various approaches on how it can be realized.

Version A: Quick 'n Dirty

This version was the quick and dirty solution I came up with. Credits to Chris
Austin for suggesting the usage of theApplicationContext class.

Preparations
  1. Create a new empty Windows Forms project.
  2. Add a new Form (for your splash screen and name it SplashForm).
1. Moving the Applications entry procedure

This is not required, but helps a beginning developer understand that the Main() entry point and
the Form1 class into which it is put by default are not necessarily coupled. So let's create a new class called AppLoader and put the entry point in there. Once done, the class should look like this:

public class AppLoader{public AppLoader(){}[STAThread]static void Main(){}}

Once completed, remove the code from your Form1.cs so that you don't end up having 2 entry points.

2. Creating the Splash Screen

Just create a new Windows Form, place a PictureBox on it and set a couple of properties just to make it look nicer. The form should be centered on the screen (StartPosition),
be topmost (TopMost) and shouldn't have a border (FormBorderStyle).
As for the PictureBox, set the Dock property to Fill and set the Image property
to your splash image. That's it. In real life, you might want to write some code to display the application name, it's version, the registered user and a copyright notice, etc.

3. Modifying the MainForm's code

Now we need to do some modifications to the Form1 class. Since some initialization code can be put into the class constructor (such as reading files, etc.) some can't (like creating controls) since this is
not available in the constructor. So you can't for example add controls to a forms Controls collection. Lets add a new public method (e.g. public
void PreLoad(){...}
). This function should look somewhat like this:

public void PreLoad(){if (_Loaded){//just return. this code can't execute twice!return;}//do your initialization here//...//flag that we have loaded all we need._Loaded = true;}

The _Loaded variable is a private bool, which should be initialized to false.
You definitely should check this flag in your main forms OnLoad() override (which is called just before the form is shown the first time). For example:

protected override void OnLoad(System.EventArgs e){if (!_Loaded){//good idea to throw an exception here.         //    the form shouldn't be shown w/o being initialized!return;}}
4. Modifying the AppLoader class

Here is the code for the AppLoader class. See the comments for information.

public class AppLoader{private static ApplicationContext context;private static SplashForm sForm = new SplashForm();private static MainForm mForm  = new MainForm();[STAThread]static void Main(string[] args){//first we retrieve an application context for usage in the         //    OnAppIdle event handlercontext = new ApplicationContext();//then we subscribe to the OnAppIdle event...Application.Idle += new EventHandler(OnAppIdle);//...and show our SplashFormsForm.Show();//instead of running a window, we use the contextApplication.Run(context);}private static void OnAppIdle(object sender, EventArgs e){if(context.MainForm == null){//first we remove the eventhandlerApplication.Idle -= new EventHandler(OnAppIdle);//here we preload our formmForm.PreLoad();//now we set the main form for the context...context.MainForm = mForm;//...show it...context.MainForm.Show();//...and hide the splashscreen. done!sForm.Close();sForm = null;}}}

Version B: Multithreaded

This version entirely based on Jabes idea. For more information read the
Messages below. Thanks again to Jabes for letting me use his stuff in this article!

In this version, the SplashForm is shown in a separate thread and displays the current loading status (like in PhotoShop). You will want to multi-thread your splash screen if it is going to be
on-screen for any length of time; by running the splash screen from its own message pump, screen redraws and other windows messages are processed correctly giving a more professional impression.

Preparations
  1. Create a new empty Windows Forms project.
  2. Add a new Form (for your splash screen and name it SplashForm).
  3. Repeat the steps from the previous Section which create the AppLoader class containing the entry point for the application. Leave the Method Body for Main() empty
    for now. Don't forget to remove the Main() method from the Form1 code!
1. Modify the SplashForm

In order to display the loading status on the form, we need to place a label on the form. For our example we call it lStatusInfo. Additionally we create a get/set Property named StatusInfo. After
that we introduce a private string member called _StatusInfo which maps directly to the Property. The Property implementation should look like this:

public string StatusInfo {set {_StatusInfo = value;ChangeStatusText();}get {return _StatusInfo;}}

ChangeStatusText() is a helper function which will be called each time the StatusInfo should be updated.
It's implementation should look like this:

public void ChangeStatusText() {try {if (this.InvokeRequired) {this.Invoke(new MethodInvoker(this.ChangeStatusText));return;}lStatusInfo.Text = _StatusInfo;}catch (Exception e) {//do something here...}}

The check for the InvokeRequired property is necessary because controls are not thread safe. So if
you call a method on a control from a different thread (then the one which created the control) without marshalling the call into the proper thread, weird things might happen.

That's it. Let's create the Splasher class which maintains Thread creation, start and stop.

2. Creating the Splasher class

The static members Show()Close() and
the Status property can be used as their names suggest to show and close the SplashWindow as well as to update the loading status displayed on the SplashForm (using
the StatusInfoProperty previously created).

Here is what the implementation of the class looks like:

public class Splasher{static SplashForm MySplashForm = null;static Thread MySplashThread = null;//internally used as a thread function - showing the form and//starting the messageloop for itstatic void ShowThread(){MySplashForm = new SplashForm();Application.Run(MySplashForm);}//public Method to show the SplashFormstatic public void Show(){if (MySplashThread != null)return;MySplashThread = new Thread(new ThreadStart(Splasher.ShowThread));MySplashThread.IsBackground = true;MySplashThread.ApartmentState = ApartmentState.STA;MySplashThread.Start();}//public Method to hide the SplashFormstatic public void Close(){if (MySplashThread == null) return;if (MySplashForm == null) return;try{MySplashForm.Invoke(new MethodInvoker(MySplashForm.Close));}catch (Exception){}MySplashThread = null;MySplashForm = null;}//public Method to set or get the loading Statusstatic public string Status{set{if (MySplashForm == null){return;}MySplashForm.StatusInfo = value;}get{if (MySplashForm == null){throw new InvalidOperationException("Splash Form not on screen");}return MySplashForm.StatusInfo;}}}

Ok, let’s look at what we have here:

The Show() method will create a new Thread using the static ShowThread function
as a target. This function will simply show the Form and start a MessageLoop for it. The Close() method will again marshal a call to the SplashForms Close() method
into the appropriate thread thus causing the form to close. The Status Property can be used to retrieve or update the StatusInfo displayed on the SplashScreen.

Here are some simple examples of their usage:

...//note that there is no instance required since those functions are staticSplasher.Show();//shows the SplashScreen        //sets the status info displayed on the SplashScreenSplasher.Status = "Initializing Database Connection...";Splasher.Close();//closes the SplashScreen...

Modifying the AppLoader class

In order to use the Splasher class we have to modify our AppLoader class appropriately:

public class AppLoader{public AppLoader(){}[STAThread]static void Main(string[] args){Splasher.Show();DoStartup(args);Splasher.Close();}static void DoStartup(string[] args){//do whatever you need to doForm1 f = new Form1();Application.Run(f);}}

First we show the SplashForm and set the initial StatusInfo text.
Then we call DoStartup(), a good place to put any initialization code which doesn't require a form to be created.

Why moving the Startup Code into an extra function you might ask. The answer is simple: Since the Jitter works on a per function basis, it won’t need to do too much code before your Splash-Screen
is actually getting shown on the screen.

To ensure that after you main Application form is loaded, it actually gets focused; you might want to put the following statement into the Form1 OnLoad override:

this.Activate();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.