c# 进度条 ProgressBar的简单例子

发布时间:2020-04-01编辑:脚本学堂
为大家提供一个c#用ProgressBar实现进度条的例子,有需要的朋友,可以参考下。

代码如下:
 

复制代码 代码示例:
///
/// 进度条 ProgressBar
/// www.jb200.com
///
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Diagnostics;
 
namespace Update
{
public partial class FrmUpdate : Form
{
//设置进度条的委托
public delegate void SetProgressDelegate(int maximum, int value, string msg);
//声明进度条事件
public event SetProgressDelegate SetProgress;
//关闭进度条的委托
public delegate void CloseProgressDelegate();
//声明关闭进度条事件
public event CloseProgressDelegate CloseProgress;
UpdateService.Service service = new UpdateService.Service();//webservice服务
public FrmUpdate()
{
InitializeComponent();
}
 
private void FrmUpdate_Load(object sender, EventArgs e)
{
try
{
//用子线程工作
Thread t = new Thread(new ThreadStart(DownLoad));
t.IsBackground = true;//设为后台线程
t.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 下载更新
/// </summary>
private void DownLoad()
{
try
{
SetProgress += new SetProgressDelegate(FrmUpdate_SetProgress);
string url = service.GetUrl();//获取下载地址
string[] files = service.GetFiles();//获取下载文件数组
WebClient wc = new WebClient();
for (int i = 0; i < files.Length; i++)
{
wc.DownloadFile(url + files[i], files[i]);//下载
FrmUpdate_SetProgress(files.Length, i + 1, files[i] + "(" + (i + 1).ToString() + "/" + files.Length + ")");//调用设置进度条事件
}
wc.Dispose();
CloseProgress += new CloseProgressDelegate(FrmUpdate_CloseProgress);
FrmUpdate_CloseProgress();//调用关闭进度条事件
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 实现设置进度条事件
/// </summary>
/// <param name="maximum">进度条最大值</param>
/// <param name="value">进度条当前值</param>
private void FrmUpdate_SetProgress(int maximum, int value, string msg)
{
if (this.Invokerequired)
{
this.Invoke(new SetProgressDelegate(FrmUpdate_SetProgress), new object[] { maximum, value, msg });
}
else
{
this.progressBar1.Maximum = maximum;//设置进度条最大值
this.progressBar1.Value = value;//设置进度条当前值
label1.Text = msg;//设置显示的信息
}
}
 
/// <summary>
/// 实现关闭进度条事件
/// </summary>
 /// www.jb200.com
private void FrmUpdate_CloseProgress()
{
if (this.InvokeRequired)
{
this.Invoke(new CloseProgressDelegate(FrmUpdate_CloseProgress), null);
}
else
{
MessageBox.Show("升级成功!");
IniClass ini = new IniClass(Application.StartupPath + @"Update.ini");
string serviceVersion = service.GetVersion();//服务端版本
ini.IniWriteValue("update", "version", serviceVersion);//更新成功后将版本写入配置文件
Application.Exit();//退出升级程序
Process.Start("Main.exe");//打开主程序Main.exe
}
}
}
}