VB.NET进度条问题

时间:2014-07-19 16:52:35

标签: vb.net visual-studio-2010 file-io progress-bar sleep

我希望在单击按钮时使用进度条打开另一个表单。到目前为止,执行冻结了几秒钟,然后进度条表单打开,进度条已满,然后关闭。我希望主窗体暂停执行,以便在进度条完成后才能写入文件。这是我的代码:

  

主要课程:

Private Sub btnWriteFile_Click(sender As Object, e As EventArgs) Handles btnWriteFile.Click
    If hasUserEnteredFileName() = True Then 'don't worry about this
        If reversedString IsNot Nothing Then 'or this
            FileWriting.Show() 'the progress bar class
            Dim sw As StreamWriter = File.CreateText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" & fileName.Text & ".txt")
            sw.Write(reversedString)
            sw.Flush()
            sw.Close()
        End If
    End If
End Sub
  

进度条类:

Private Sub FileWriting_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ProgressBar1.Minimum = 1
    ProgressBar1.Maximum = 100
    For i = ProgressBar1.Minimum To ProgressBar1.Maximum - 2
        Sleep(10)
        ProgressBar1.Value += 2
        ProgressBar1.Value -= 1
    Next i
End Sub

1 个答案:

答案 0 :(得分:0)

如果不使用Multithreading就无法执行此类操作,因此我更改了代码的某些部分,如下所示:

Public Class FileWriting

Private Sub FileWriting_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    BackgroundWorker1.RunWorkerAsync()
End Sub

Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    Me.Invoke(New MethodInvoker(Sub() setprogressbarminmax()))
    Dim min_value As Integer = 0
    Dim max_value As Integer = 0

    Me.Invoke(New MethodInvoker(Sub() min_value = ProgressBar1.Minimum))
    Me.Invoke(New MethodInvoker(Sub() max_value = ProgressBar1.Maximum))

    For i = min_value To max_value
        System.Threading.Thread.Sleep(10)
        If i < 99 Then
            Me.Invoke(New MethodInvoker(Sub() setprogvalue()))
        End If
    Next i
End Sub

Private Sub setprogressbarminmax()
    ProgressBar1.Minimum = 1 : ProgressBar1.Maximum = 100
End Sub

Private Sub setprogvalue()
    ProgressBar1.Value += 2
    ProgressBar1.Value -= 1
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    Me.Close()
End Sub 

End Class