【问题标题】:How to show progress bar in windows application?如何在windows应用程序中显示进度条?
【发布时间】:2012-05-18 04:08:46
【问题描述】:

我正在使用 c# 开发一个 Windows 应用程序。

我有一个表单和一个包含所有方法的类。

我在类中有一个方法,我在其中处理 arraylist 中的一些文件。我想为此文件处理调用进度条方法,但它不起作用。

任何帮助

PFB 我的代码 sn-p:

public void TraverseSource()
{
    string[] allFiles1 = Directory.GetFiles(sourcePath, "*.xml", SearchOption.AllDirectories);

    var allFiles = new ArrayList();
    var length = allFiles.Count;
    foreach (string item in allFiles1)
    {
        if (!item.Substring(item.Length - 6).Equals("MD.xml"))
        {
            allFiles.Add(item);

            // Here i want to invoke progress bar which is in form
        }
    }
}

【问题讨论】:

    标签: c# winforms progress-bar


    【解决方案1】:

    您需要使用BackgroundWorker 组件,其中DoWork 处理程序包含您的实际工作(string[] allFiles1 部分及其他部分)。它看起来像这样:

    public void TraverseSource()
    {
        // create the BackgroundWorker
        var worker = new BackgroundWorker
                           {
                              WorkerReportsProgress = true
                           };
    
        // assign a delegate to the DoWork event, which is raised when `RunWorkerAsync` is called. this is where your actual work should be done
        worker.DoWork += (sender, args) => {
           string[] allFiles1 = Directory.GetFiles(sourcePath, "*.xml", SearchOption.AllDirectories);
    
            var allFiles = new ArrayList();
    
            foreach (var i = 0; i < allFiles1.Length; i++)
            {
                if (!item.Substring(item.Length - 6).Equals("MD.xml"))
                {
                    allFiles.Add(item);
                    // notifies the worker that progress has changed
                    worker.ReportProgress(i/allFiles.Length*100);
                }
            }
        };
        // assign a delegate that is raised when `ReportProgress` is called. this delegate is invoked on the original thread, so you can safely update a WinForms control
        worker.ProgressChanged += (sender, args) => {
           progressBar1.Value = args.ProgressPercentage;
        };
    
        // OK, now actually start doing work
        worker.RunWorkerAsync();
    
    }
    

    【讨论】:

    • 谢谢..你能分享一些代码来展示我应该如何实现它吗?
    • @SiKni8 Implicitly typed local variables 于 2007 年作为 C# 3.0 和 .NET 3.5 的一部分添加。
    • @HackedByChinese 并不是说​​听起来粗鲁:) 只是想使用您的代码,仅此而已。感谢您的澄清。
    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多