How do I show a “Loading . . . please wait” message in Winforms for a long loading form?

前端 未结 12 654
一生所求
一生所求 2020-12-04 17:29

I have a form that is very slow because there are many controls placed on the form.

As a result the form takes a long time to loaded.

How do I load the fo

12条回答
  •  余生分开走
    2020-12-04 18:20

    I looked at most the solutions posted, but came across a different one that I prefer. It's simple, doesn't use threads, and works for what I want it to.

    http://weblogs.asp.net/kennykerr/archive/2004/11/26/where-is-form-s-loaded-event.aspx

    I added to the solution in the article and moved the code into a base class that all my forms inherit from. Now I just call one function: ShowWaitForm() during the frm_load() event of any form that needs a wait dialogue box while the form is loading. Here's the code:

    public class MyFormBase : System.Windows.Forms.Form
    {
        private MyWaitForm _waitForm;
    
        protected void ShowWaitForm(string message)
        {
            // don't display more than one wait form at a time
            if (_waitForm != null && !_waitForm.IsDisposed) 
            {
                return;
            }
    
            _waitForm = new MyWaitForm();
            _waitForm.SetMessage(message); // "Loading data. Please wait..."
            _waitForm.TopMost = true;
            _waitForm.StartPosition = FormStartPosition.CenterScreen;
            _waitForm.Show();
            _waitForm.Refresh();
    
            // force the wait window to display for at least 700ms so it doesn't just flash on the screen
            System.Threading.Thread.Sleep(700);         
            Application.Idle += OnLoaded;
        }
    
        private void OnLoaded(object sender, EventArgs e)
        {
            Application.Idle -= OnLoaded;
            _waitForm.Close();
        }
    }
    

    MyWaitForm is the name of a form you create to look like a wait dialogue. I added a SetMessage() function to customize the text on the wait form.

提交回复
热议问题