C#利用委托和ProgressBar实现进度条显示

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/funkstill/article/details/88424472

问题描述:

    项目需要,处理数据时间较长,有显示进度需求。

解决方案:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Threading;
namespace learnProcessBar
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private delegate void DelSetPro(int pro, ProgressBar proBar);//设置进度条进度的委托方法
        private delegate void DelSetProVisi(ProgressBar proBar);//设置进度条消失的委托方法
        /// <summary>
        /// 设置ProgressBar的进度。
        /// </summary>
        /// <param name="pro"></param>
        /// <param name="proBar"></param>
        private void SetProgressMessage(int pro, ProgressBar proBar)
        {
            //如果当前调用方不是创建控件的一方,则需要使用this.Invoke()
            //在这里,ProgressBar控件是由主线程创建的,所以子线程要对该控件进行操作
            //必须执行this.InvokeRequired进行判断。
            if (this.InvokeRequired)
            {
                DelSetPro setPro = new DelSetPro(SetProgressMessage);
                this.Invoke(setPro, new object[] { pro, proBar });
            }
            else
            {
                proBar.Value = Convert.ToInt32(pro);
            }
        }

        /// <summary>
        /// 让控件ProgressBar消失。
        /// </summary>
        /// <param name="pro"></param>
        private void SetProgressBarVisi(ProgressBar pro)
        {
            if (this.InvokeRequired)
            {
                DelSetProVisi setProVisi = new DelSetProVisi(SetProgressBarVisi);
                this.Invoke(setProVisi, new object[] { pro });
            }
            else
            {
                pro.Visible = false;
            }
        }
        /// <summary>
        /// 操作ProgressBar01
        /// </summary>
        private void SleepForProgressBar01()
        {
            for (int i = 1; i <= 100; i++)
            {
                Thread.Sleep(10);
                SetProgressMessage(i, progressBar1);
            }
            DialogResult dr01 = MessageBox.Show("ProgressBar01 has been finished!");
            if (dr01.Equals(DialogResult.OK))
            {
                SetProgressBarVisi(progressBar1);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Thread pro01Thread = new Thread(new ThreadStart(SleepForProgressBar01));
            pro01Thread.Start();
        }
    }
}

效果:

猜你喜欢

转载自blog.csdn.net/funkstill/article/details/88424472
今日推荐