当前位置:编程学习 > C#/ASP.NET >>

请问这个进度条方法怎么用 急急急

如何弹出一个模式窗口来显示进度条 

最近看了好多人问这方面的问题,以前我也写过一篇blog,里面说了如何在子线程中控制进度条。但目前大多数环境,需要弹出模式窗口,来显示进度条,那么只需要在原先的基础上稍作修改即可。
 
首先是进度条窗体,需要在上面添加进度条,然后去掉ControlBox。除此外,还要增加一个方法,用来控制进度条的增加幅度,具体如下:
    ///<summary>
    /// Increase process bar
    ///</summary>
    ///<param name="nValue">the value increased</param>
    ///<returns></returns>
    public bool Increase( int nValue )
    {
        if( nValue > 0 )
        {
            if( prcBar.Value + nValue < prcBar.Maximum )
            {
                prcBar.Value += nValue;
                return true;
            }
            else
            {
                prcBar.Value = prcBar.Maximum;
                this.Close();
                return false;
            }
        }
        return false;
    }
 
接着就是主窗体了,如何进行操作了,首先需要定义两个私有成员,一个委托。其中一个私有成员是保存当前进度条窗体对象,另一个是保存委托方法(即增加进度条尺度),具体如下:
    private frmProcessBar myProcessBar = null;
    private delegate bool IncreaseHandle( int nValue );
    private IncreaseHandle myIncrease = null;
 
接着要在主窗体中提供函数来打开进度条窗体,如下:
    ///<summary>
    /// Open process bar window
    ///</summary>
    private void ShowProcessBar()
    {
        myProcessBar = new frmProcessBar();
 
        // Init increase event
        myIncrease = new IncreaseHandle( myProcessBar.Increase );
        myProcessBar.ShowDialog();
        myProcessBar = null;
    }
 
那么现在就可以开始创建线程来运行,具体如下:
    ///<summary>
    /// Sub thread function
    ///</summary>
    private void ThreadFun()
    {
        MethodInvoker mi = new MethodInvoker( ShowProcessBar );
        this.BeginInvoke( mi );
 
        Thread.Sleep( 1000 );//Sleep a while to show window
 
        bool blnIncreased = false;
        object objReturn = null;
        do
        {
            Thread.Sleep( 50 );
            objReturn = this.Invoke( this.myIncrease, 
                new object[]{ 7} );//传的参数为整型7(IncreaseHandle( int nValue ))
            blnIncreased = (bool)objReturn ;
        }
        while( blnIncreased );
    }
       
       注意以上,在打开进度条窗体和增加进度条进度的时候,一个用的是BeginInvoke,一个是Invoke,这里的区别是BeginInvoke不需要等待方法运行完毕,而Invoke是要等待方法运行完毕。还有一点,此处用返回值来判断进度条是否到头了,如果需要有其他的控制,可以类似前面的方法来进行扩展。
 
启动线程,可以如下:
    Thread thdSub = new Thread( new ThreadStart( ThreadFun ) );
    thdSub.Start();
 
这样,一个用模式打开进度条窗体就做完了。





我使用的是

  private void Form1_Load(object sender, EventArgs e)
{
   Thread thdSub = new Thread(new ThreadStart(ThreadFun));
                thdSub.Start();
执行代码。。。。。

 myIncrease.Invoke(100);








但是不能用,不知道为什么? --------------------编程问答-------------------- 给一个以前写的项目功能片段,你自己参考一下。这是用来复制文件的,你可以按照自己的需求做相应的修改。整个窗体文件都给你,窗体名称为:FormatCopy。

FormatCopy.cs 代码:


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

namespace Server
{
    public partial class FormCopy : Form
    {
        string sourceDir = "";
        string desDir = "";
        Thread thread;
        bool flag = false;

        //原目录
        public string SourceDir
        {
            get { return this.sourceDir; }
            set { this.sourceDir = value; }
        }

        //目标目录
        public string DestDir
        {
            get { return this.desDir; }
            set { this.desDir = value; }
        }

        public FormCopy()
        {
            InitializeComponent();
        }

        private void FormCopy_Load(object sender, EventArgs e)
        {
            //在线程中处理文件复制可大大提高程序的运行效率
            thread = new Thread(new ThreadStart(Copy));
            thread.Start();
        }

        private void Copy()
        {
            DirectoryInfo dir = new DirectoryInfo(sourceDir);
            CopyDirectorysAndFiles(desDir, dir);

            flag = true;
            this.Close();
        }

        /// <summary>
        /// 复制指定文件夹中的子文件夹和文件
        /// </summary>
        /// <param name="destDir">目标文件夹路径</param>
        /// <param name="sourceDir">DirectoryInfo 对象</param>
        private void CopyDirectorysAndFiles(string destDir, DirectoryInfo sourceDir)
        {
            string[] str = desDir.Split(new string[] { "\\" }, StringSplitOptions.None);

            if (destDir.LastIndexOf('\\') != (destDir.Length - 1))
            {
                destDir += "\\";
            }

            string destPath = destDir + sourceDir.Name + "\\";
            if (!Directory.Exists(destPath))
            {
                Directory.CreateDirectory(destPath);
            }
            
            //复制文件
            FileInfo[] files = sourceDir.GetFiles();
            //文件总量
            int length = 0;
            for (int i = 0; i < files.Length; i++)
                length += (int)files[i].Length;
            
            this.progressBar1.Value = 0;
            this.progressBar1.Maximum = length;

            foreach (FileInfo file in files)
            {
                CopyFile(file, sourceDir.Name, destPath);
                this.progressBar1.Value += (int)file.Length;

                //此语句大大提高了程序的运行效率
                Thread.Sleep(10);
            }

            DirectoryInfo[] dirs = sourceDir.GetDirectories();
            foreach (DirectoryInfo dirInfo in dirs)
            {
                CopyDirectorysAndFiles(destPath, dirInfo);
            }
        } 

        /// <summary>
        /// 文件复制函数(将被复制的文件按每包 10 兆大小将原文件分包,这样便于大容量文件的操作)
        /// </summary>
        /// <param name="file">FileInfo 文件对象</param>
        /// <param name="src">原文件所在目录</param>
        /// <param name="dest">目标文件所在目录</param>
        private void CopyFile(FileInfo file, string src, string dest)
        {
            if (!flag)
            {
                string[] str = dest.Split(new string[] { "\\" }, StringSplitOptions.None);
                this.label1.Text = file.Name + "\r\n\r\n从 \'" + src + "\' 到 \'" + str[str.Length - 2] + "\'";

                //打开并读取文件
                FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);

                int size = 1024 * 1024 * 10; //按每包 10 兆大小将原文件分包
                int length = (int)fs.Length; //原文件大小
                int package = length / size; //数据包的数量
                int m = length % size; //剩余数据包的数据量

                //二进制读取器
                BinaryReader reader = new BinaryReader(fs);
                //创建新文件
                fs = new FileStream(dest + file.Name, FileMode.Create, FileAccess.Write);

                //分包逐一读写文件(边读边写)
                for (int i = 1; i <= package; i++)
                {
                    //按指定数据包的大小读取数据
                    byte[] buffer = reader.ReadBytes(size);
                    //将读取的数据写入新文件中
                    fs.Write(buffer, 0, buffer.Length);
                }

                //如果有未尽数据包则继续读写
                if (m != 0)
                {
                    byte[] buffer = reader.ReadBytes(m);

                    fs.Write(buffer, 0, buffer.Length);
                }

                reader.Close();
                fs.Close();
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            flag = true;
            thread.Abort();
            this.Close();
        }

        private void FormCopy_FormClosed(object sender, FormClosedEventArgs e)
        {
            thread.Abort();
            flag = true;
        }
    }
}

窗体 FormCopy 设计器代码:
namespace Server
{
    partial class FormCopy
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.progressBar1 = new System.Windows.Forms.ProgressBar();
            this.buttonCancel = new System.Windows.Forms.Button();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.label1 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // progressBar1
            // 
            this.progressBar1.Location = new System.Drawing.Point(27, 107);
            this.progressBar1.Name = "progressBar1";
            this.progressBar1.Size = new System.Drawing.Size(297, 20);
            this.progressBar1.TabIndex = 1;
            // 
            // buttonCancel
            // 
            this.buttonCancel.Location = new System.Drawing.Point(330, 106);
            this.buttonCancel.Name = "buttonCancel";
            this.buttonCancel.Size = new System.Drawing.Size(75, 23);
            this.buttonCancel.TabIndex = 2;
            this.buttonCancel.Text = "取  消";
            this.buttonCancel.UseVisualStyleBackColor = true;
            this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
            // 
            // pictureBox1
            // 
            this.pictureBox1.Image = global::Server.Properties.Resources.FILEMOVE;
            this.pictureBox1.Location = new System.Drawing.Point(27, 0);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(352, 54);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(29, 63);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(41, 12);
            this.label1.TabIndex = 4;
            this.label1.Text = "label1";
            // 
            // FormCopy
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(409, 137);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.buttonCancel);
            this.Controls.Add(this.progressBar1);
            this.Controls.Add(this.pictureBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "FormCopy";
            this.Text = "正在复制....";
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.FormCopy_FormClosed);
            this.Load += new System.EventHandler(this.FormCopy_Load);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.ProgressBar progressBar1;
        private System.Windows.Forms.Button buttonCancel;
        private System.Windows.Forms.Label label1;
    }
}
--------------------编程问答-------------------- 窗体名称:FormCopy,上面写错了。
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,