Thứ Năm, 8 tháng 12, 2011

// // Leave a Comment

Splash Form C# - Tạo form chờ

Đôi khi bạn không muốn đợi quá lâu để cho 1 chương trình ứng dụng của bạn load xong dữ liệu. Hãy tạo ra một màn hình chờ riêng của bạn cho người dùng thấy rằng, à chương trình này đang khởi động. Đoạn mã snippet dưới đây cho phép bạn tạo ra một form chạy độc lập với form chính và sẽ được đóng lại khi dữ liệu chương trình được load xong toàn bộ.


    public partial class F003_Splash : Form
    {
        private F003_Splash()
        {
            InitializeComponent();
        }

        // Thredding.
        private static Thread _splashThread;
        private static F003_Splash _splashForm;


        // Show the Splash Screen (Loading...)     
        public static void ShowSplash()
        {
            if (_splashThread == null)
            {
                // show the form in a new thread           
                _splashThread = new Thread(new ThreadStart(DoShowSplash));
                _splashThread.IsBackground = true;
                _splashThread.Start();
            }
        }

        // Called by the thread   
        private static void DoShowSplash()
        {
            if (_splashForm == null)
            {
                _splashForm = new F003_Splash();
                _splashForm.StartPosition = FormStartPosition.CenterScreen;
                _splashForm.TopMost = true;
            }
            // create a new message pump on this thread (started from ShowSplash)       
            Application.Run(_splashForm);
        }

        // Close the splash (Loading...) screen   
        public static void CloseSplash()
        {
            // Need to call on the thread that launched this splash       
            if (_splashForm.InvokeRequired)
                _splashForm.Invoke(new MethodInvoker(CloseSplash));
            else
                Application.ExitThread();
        }
    }


Cách sử dụng như sau.


    try
    {
        F003_Splash.ShowSplash();
        LoadComponent();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        // EndFlashing
        F003_Splash.CloseSplash();
        this.Activate();
    }



Mình đã áp dụng thử vào bài tập lớn: Đăng ký đào tạo tín chỉ
Bạn có thể tham khảo tại đây, download: http://www.mediafire.com/?fh6jcjmvy132d32
Cơ sở dữ liệu của nó thiết kế hơi xịt, không comment nhá!

0 comments: