首页 > 解决方案 > 如何在 WinForms 中制作文件下载进度条?

问题描述

我正在用 CefSharp 制作一个网络浏览器。我在 2 天前刚刚实现了下载,但下载没有进度条。如何让进度条显示下载进度?

标签: winformsdownloadprogress-bar

解决方案


编辑:让事情更清楚

将 ProgressBar 控件添加到您的表单,并在它旁边添加一个 BackgroundWorker 组件到您的表单。首先弄清楚你的文件大小:

Int64 bytes_total= Convert.ToInt64(client.ResponseHeaders["Content-Length"])

这是来自 Alex 的惊人答案的代码,可以在这里找到:

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.WorkerReportsProgress = true;
}

private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    //Replace this code with a way to figure out how much of the file you have already downloaded and then use backgroundworker1.ReportProgress and send the percentage completion of the file download.
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);
    }
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

推荐阅读