简体   繁体   English

C#进度栏-无法将其包围

[英]C# Progress bar - can't wrap my head around it

I have a program that takes loops through files in a folder, creates a new folder elsewhere with that file name, then puts a common file in that folder. 我有一个程序可以循环访问文件夹中的文件,在该文件名的其他位置创建一个新文件夹,然后在该文件夹中放置一个公用文件。 rinse repeat until we are done with whats in that folder (listed in a listbox). 重复冲洗直到完成该文件夹中的内容(在列表框中列出)。

I decided I want to be fancy and have a progress bar. 我决定要花哨并准备进度条。 I conceptually understand that I am increment the count by one (to the listbox.items.count ) for each iteration.. which I have coded and works well. 我从概念上理解,对于每次迭代,我都将计数增加一个(到listbox.items.count )。

I also understand that the DoWork event is what counts for the progress bar, how do I get the two to mesh? 我也知道DoWork事件是进度条的重要组成部分,如何使两者相互啮合? Do I pass a counter to the DoWork for each iteration? 每次迭代我都将计数器传递给DoWork吗?

I am just missing the bridge from my main code loop to the DoEvents counter. 我只是缺少从我的主代码循环到DoEvents计数器的桥梁。

Use a backgroundworker as shown: 如图所示使用背景工:

 BackgroundWorker worker = new BackgroundWorker();
 worker.WorkerReportsProgress = true;
 worker.DoWork += new DoWorkEventHandler(update_DoWork);
 worker.ProgressChanged += new ProgressChangedEventHandler(update_ProgressChanged);
 worker.RunWorkerAsync();

You need a ProgressChangedEventHandler. 您需要一个ProgressChangedEventHandler。 Then you will need to use ReportProgress when you want to update the progress bar (this will be in the DoWork method). 然后,当您要更新进度条时(这将在DoWork方法中),您将需要使用ReportProgress。 This method will call the ProgressChangedEventHandler. 此方法将调用ProgressChangedEventHandler。

int percentProgress = 10;
worker.ReportProgress(percentProgress)

An example of a ProgressChangedEventHandler: ProgressChangedEventHandler的示例:

 private void update_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
           progressBar.Value = (e.ProgressPercentage);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM