本文實例講述了c#制作簡單啟動畫面的方法。分享給大家供大家參考。具體分析如下:
啟動畫面是程序啟動加載組件時一個讓用戶稍微耐心等待的提示框。一個好的軟件在有啟動等待需求時必定做一個啟動畫面。啟動畫面可以讓用戶有心理准備來接受程序加載的緩慢,還可以讓用戶知道加載的進度和內容。本文只是記錄最簡單的構架。
VS2010創建一個C# Windows窗體應用程序,將主窗體改名為FormMain,再創建一個窗體起名為SplashScreen。向程序中加載一個圖片作為啟動畫面,如下圖
/// <summary> /// 啟動畫面 /// </summary> public partial class SplashScreen : Form { /// <summary> /// 啟動畫面本身 /// </summary> static SplashScreen instance; /// <summary> /// 顯示的圖片 /// </summary> Bitmap bitmap; public static SplashScreen Instance { get { return instance; } set { instance = value; } } public SplashScreen() { InitializeComponent(); // 設置窗體的類型 const string showInfo = "啟動畫面:我們正在努力的加載程序,請稍后..."; FormBorderStyle = FormBorderStyle.None; StartPosition = FormStartPosition.CenterScreen; ShowInTaskbar = false; bitmap = new Bitmap(Properties.Resources.SplashScreen); ClientSize = bitmap.Size; using (Font font = new Font("Consoles", 10)) { using (Graphics g = Graphics.FromImage(bitmap)) { g.DrawString(showInfo, font, Brushes.White, 130, 100); } } BackgroundImage = bitmap; } protected override void Dispose(bool disposing) { if (disposing && (components != null)) { if (bitmap != null) { bitmap.Dispose(); bitmap = null; } components.Dispose(); } base.Dispose(disposing); } public static void ShowSplashScreen() { instance = new SplashScreen(); instance.Show(); } }
然后在主程序啟動時調用
static class Program { /// <summary> /// 應用程序的主入口點。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // 啟動 SplashScreen.ShowSplashScreen(); // 進行自己的操作:加載組件,加載文件等等 // 示例代碼為休眠一會 System.Threading.Thread.Sleep(3000); // 關閉 if (SplashScreen.Instance != null) { SplashScreen.Instance.BeginInvoke(new MethodInvoker(SplashScreen.Instance.Dispose)); SplashScreen.Instance = null; } Application.Run(new FormMain()); } }