进度条案例
1:递归查询目录,包含子目录
2:采用委托方案与form窗体交互。
3:此案例可扩展到:复制、移动、批量命名、或查询等对象文件的操作。
源代码如下:
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.IO; using System.Threading; using System.Diagnostics; namespace speedDemo { public partial class MainForm : Form { private bool isContionsZi = false; private string findFile = string.Empty; public MainForm() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; this.CenterToScreen(); } void Panel5SizeChanged(object sender, EventArgs e) { // 20 10 /2=5 panelMin.Left = (panelMax.Width - panelMin.Width) / 2; } void Button1Click(object sender, EventArgs e) { isContionsZi = checkBox.Checked; findFile = selectFile.Text; findFile = findFile.Trim(); if(findFile==null || "".Equals(findFile)) { MessageBox.Show("路径为空"); return; }else if(!Directory.Exists(findFile)) { MessageBox.Show("无法访问的路径或不是目录文件"); return; } button1.Enabled = false; masShow.Text = ""; textBox.Text = ""; Thread t = new Thread(new ThreadStart(aa)); t.Start(); } public void aa() { //算出总数量,求出百分比 string path = findFile; DirectoryInfo info = new DirectoryInfo(path); FileSystemInfo[] fsif = info.GetFileSystemInfos(); List<string> array = new List<string>(); getSum(fsif,array); progressBar.Maximum = array.Count; //回显到控制台 fildDir(array); } public void getSum(FileSystemInfo[] fsif,List<string> array) { foreach (FileSystemInfo fs in fsif) { array.Add(fs.FullName); if(isContionsZi)//是否包含子目录 { DirectoryInfo direct = fs as DirectoryInfo; if(direct!=null) { getSum(direct.GetFileSystemInfos(),array); } } } } public void fildDir(List<string> array) { Stopwatch watch = new Stopwatch(); watch.Start(); int sum = array.Count; //开始委托一个任务。 ((Action)delegate() { System.Threading.Thread.Sleep(1000); for (int i = 1; i <=sum; i++) { this.Invoke((Action)delegate() { //控件没有被释放 if(!IsDisposed){ textBox.AppendText(array[i-1]+"\r\n"); } }); progressBar.Value = i; masShow.Text = ((double)i/sum).ToString("P"); System.Threading.Thread.Sleep(500); } //执行结束后调用isRunTask方法收尾,传递多个参数 }).BeginInvoke(new AsyncCallback(isRunTask),new object[]{watch,array}); } public void isRunTask(IAsyncResult ar) { //获取委托传递的参数 object[] para = ar.AsyncState as object[]; if(para!=null && para.Length>=1) { Stopwatch watch = para[0] as Stopwatch; List<string> array = para[1] as List<string>; watch.Stop(); TimeSpan ts = watch.Elapsed; MessageBox.Show("一共:"+array.Count+"文件,消耗 "+ts.Days+"天"+ts.Hours+"小时"+ts.Minutes+"分"+ts.Seconds+"秒"+ts.Milliseconds+"毫秒"); button1.Enabled = true; } } void PanelDataMaxSizeChanged(object sender, EventArgs e) { panelDataMin.Left = (panelDataMax.Width-panelDataMin.Width)/2; } void PanelSpeedFuSizeChanged(object sender, EventArgs e) { //求出进度条的中间比例 panelSpeedZi.Width = masShow.Width/2; panelSpeedZi.Left = (panelSpeedFu.Width-panelSpeedZi.Width)/2; } } }演示图片:
原文:http://blog.csdn.net/hubiao_0618/article/details/21702783