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

前端 未结 12 614
一生所求
一生所求 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:10

    The best approach when you also have an animated image is this one:

    1- You have to create a "WaitForm" that receives the method that it will executed in background. Like this one

    public partial class WaitForm : Form
    {
        private readonly MethodInvoker method;
    
        public WaitForm(MethodInvoker action)
        {
            InitializeComponent();
            method = action;
        }
    
        private void WaitForm_Load(object sender, EventArgs e)
        {
            new Thread(() =>
            {
                method.Invoke();
                InvokeAction(this, Dispose);
            }).Start();
        }
    
        public static void InvokeAction(Control control, MethodInvoker action)
        {
            if (control.InvokeRequired)
            {
                control.BeginInvoke(action);
            }
            else
            {
                action();
            }
        }
    }
    

    2 - You can use the Waitform like this

    private void btnShowWait_Click(object sender, EventArgs e)
    {
        new WaitForm(() => /*Simulate long task*/ Thread.Sleep(2000)).ShowDialog();
    }
    

提交回复
热议问题