实现winfrom进度条及进度信息提示,winfrom程序假死处理

 功能描述:本方法实现进度条显示,方法执行信息反馈显示。用到的技术点为 线程与代理。
     
    步骤一:添加主页面。
      
 
控件名称:
button1;
 
  步骤二:主页面后台代码
        using System.Threading;//引用此命名
 
        //创建代理。
        private Form6 myProcessBar = null;//弹出的子窗体(用于显示进度条)
        private delegate bool IncreaseHandle(int nValue,string vinfo);//代理创建
        private IncreaseHandle myIncrease = null;//声明代理,用于后面的实例化代理
        private int vMax = 100;//用于实例化进度条,可以根据自己的需要,自己改变
 
        private void button1_Click(object sender, EventArgs e)
        {
            Thread thdSub = new Thread(new ThreadStart(ThreadFun));
            thdSub.Start();
        }
        private void ThreadFun()
        {
            MethodInvoker mi = new MethodInvoker(ShowProcessBar);
            this.BeginInvoke(mi);
            Thread.Sleep(100);
            object objReturn = null;
            for (int i = 0; i < vMax; i++)
            {
//该段方法可以放在具体的执行顺序里执行
                objReturn = this.Invoke(this.myIncrease, new object[] { 2, i.ToString() + "\r\n" });
                Thread.Sleep(50);
            }
        }
        private void ShowProcessBar()
        {
            myProcessBar = new Form6(vMax);
            myIncrease = new IncreaseHandle(myProcessBar.Increase);
            myProcessBar.ShowDialog();
            myProcessBar = null;
        }
 
步骤三:创建子窗体
 控件名称:
progressBar1;textBox1
 
步骤四:子窗体,后台代码
        public Form6(int vMax)
        {
            InitializeComponent();
            this.progressBar1.Maximum = vMax;
        }
        public bool Increase(int nValue,string nInfo)
        {
            if (nValue > 0)
            {
                if (progressBar1.Value + nValue < progressBar1.Maximum)
                {
                    progressBar1.Value += nValue;
                    this.textBox1.AppendText(nInfo);
                    Application.DoEvents();
                    progressBar1.Update();
                    progressBar1.Refresh();
                    this.textBox1.Update();
                    this.textBox1.Refresh();
                    return true;
                }
                else
                {
                    progressBar1.Value = progressBar1.Maximum;
                    this.textBox1.AppendText(nInfo);
                    //this.Close();//执行完之后,自动关闭子窗体
                    return false;
                }
            }
            return false;
        }

你可能感兴趣的:(.Net)