How to show an animated loading form while executing code in Windows Forms C#

后端 未结 1 1939
梦如初夏
梦如初夏 2021-01-15 18:01

I want to display an animated loading form while executing some code in the main form. The animated form is used only to show the user that an operation is executing and I w

相关标签:
1条回答
  • 2021-01-15 18:34

    If you need an animated progress form, try to use BackgroundWorker class to perform loading in an additional thread:

        public partial class MainForm : Form
        {
            /// <summary>
            /// Some progress form
            /// </summary>
            WaitForm waitForm = new WaitForm();
    
            /// <summary>
            /// https://msdn.microsoft.com/library/cc221403(v=vs.95).aspx
            /// </summary>
            BackgroundWorker worker = new BackgroundWorker();
    
            public MainForm()
            {
                InitializeComponent();
    
                worker.DoWork += (sender, args) => PerformReading();
                worker.RunWorkerCompleted += (sender, args) => ReadingCompleted();
            }
    
            /// <summary>
            /// This method will be executed in an additional thread
            /// </summary>
            void PerformReading()
            {
                //some long operation here
                Thread.Sleep(5000);
            }
    
            /// <summary>
            /// This method will be executed in a main thread after BackgroundWorker has finished
            /// </summary>
            void ReadingCompleted()
            {                        
               waitForm.Close();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                //Run reading in an additional thread
                worker.RunWorkerAsync();
                //Show progress form in a main thread
                waitForm.ShowDialog();
            }
        }
    
    0 讨论(0)
提交回复
热议问题