Windows Forms: Wait Form Dialog in C#

How to Create a Wait Form Dialog in C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "WaitFormDemo" and then click OK

wait form in c#Step 2: Create new form, then design frmWaitForm as below

wait form dialog in c#

You can design a simple main form as below

wait form dialog in c#

Step 3: Add code to handle frmWaiForm

using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WaitFormDemo
{
    public partial class frmWaitForm : Form
    {
        public Action Worker { get; set; }
        public frmWaitForm(Action worker)
        {
            InitializeComponent();
            if (worker == null)
                throw new ArgumentNullException();
            Worker = worker;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //Start new thread to run wait form dialog
            Task.Factory.StartNew(Worker).ContinueWith(t => { this.Close(); }, TaskScheduler.FromCurrentSynchronizationContext());
        }
    }
}

Add code to handle Form1

using System;
using System.Threading;
using System.Windows.Forms;

namespace WaitFormDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        void SaveData()
        {
            //Add code to process data
            for (int i = 0; i <= 500; i++)
                Thread.Sleep(10);//Simulator
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Open wait form dialog
            using(frmWaitForm frm = new frmWaitForm(SaveData))
            {
                frm.ShowDialog(this);
            }
        }
    }
}

VIDEO TUTORIALS