VB.NET从BackgroundWorker更改进度条值?

时间:2013-02-24 01:39:40

标签: vb.net

我有两个进度条。现在我在我的代码中做了一些其他的事情,这需要时间来执行,因此需要使用backgroundworker。我对如何使用backgroundworker并不太了解。我没有包含在这里的其余代码执行得很好,但progressbar值不会改变,也不会改变它们的文本。我将如何实现这一目标?

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    Dim LM As RegistryKey = Registry.LocalMachine
    Dim LM_SW As RegistryKey = LM.OpenSubKey("Software")
    Dim LM_MS As RegistryKey = LM_SW.OpenSubKey("Microsoft")
    Dim LM_Win As RegistryKey = LM_MS.OpenSubKey("Windows")
    Dim LM_CV As RegistryKey = LM_Win.OpenSubKey("CurrentVersion")
    Dim AppPaths As RegistryKey = LM_CV.OpenSubKey("App Paths")
    Dim NrOfFiles1 As Integer = AppPaths.SubKeyCount

    ProgressBar2.Maximum = NrOfFiles1
    ProgressBar1.Maximum = 100

    For Each FormatString As String In AppPaths.GetSubKeyNames()
        ProgressBar2.Value += 1 / NrOfFiles1
        ProgressBar1.Value += 1 * ProgressBar2.Value / 100 / 10
        ProgressBar1.Text = ProgressBar1.Value & "%"
        ProgressBar2.Text = ProgressBar2.Value & "%"
    Next

    ProgressBar2.Value = 0

End Sub

1 个答案:

答案 0 :(得分:2)

使用Backgroundworker的ProgressChanged事件。 在您的DoWork方法中,调用

BackgroundWorker1.ReportProgress(Percentage) 

其中百分比是整数值

然后在ProgressChanged事件中,您可以操作进度条。

Private Sub backgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles backgroundWorker1.DoWork

     Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

     '''YOUR OTHER CODE
     worker.ReportProgress(PERCENTAGE)
     '''YOUR OTHER CODE

    End Sub 

    ' This event handler updates the progress. 
    Private Sub backgroundWorker1_ProgressChanged(ByVal sender As System.Object,         ByVal e As ProgressChangedEventArgs) Handles backgroundWorker1.ProgressChanged
        ProgressBar1.Text = e.ProgressPercentage.ToString() & "%"
        ProgressBar1.Value  = e.ProgressPercentage
    End Sub