2020年5月4日 星期一

vb.net 下載檔案配合ProgressBar顯示進度 [ProgressBar with Download]

    Dim wc As System.Net.WebClient


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

        wc = New System.Net.WebClient()
        ProgressBar1.Maximum = 100
        ProgressBar1.Minimum = 0
        AddHandler wc.DownloadProgressChanged, AddressOf OnDownloadProgressChanged
        AddHandler wc.DownloadFileCompleted, AddressOf OnFileDownloadCompleted
        wc.DownloadFileAsync(New Uri("http://url.com/file.zip"), "C:\Downloads\file.zip")
    End Sub

    Private Sub OnDownloadProgressChanged(ByVal sender As Object, ByVal e As System.Net.DownloadProgressChangedEventArgs)


        Dim totalSize As Long = e.TotalBytesToReceive
        Dim downloadedBytes As Long = e.BytesReceived
        Dim percentage As Integer = e.ProgressPercentage

        ProgressBar1.Value = e.ProgressPercentage


    End Sub

    Private Sub OnFileDownloadCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)

        If e.Cancelled Then
            'Cancelled
        ElseIf Not e.Error Is Nothing Then
            'Error occured
        Else
            'File Downloaded Successfuly
            MsgBox("下載完成", 64, "完成")
        End If
    End Sub

沒有留言:

張貼留言