So first, drag a ProgressBar and a Button from the Toolbox onto the form.
Create a Click_Event for the button by double clicking it.
Add this using statement to the top of the form.
Imports System.Net
In the Click_Event, we are going to create a WebClient object to download the file.
Private Sub btnStartDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartDownload.Click
Dim client As WebClient = New WebClient
AddHandler client.DownloadProgressChanged, AddressOf client_ProgressChanged
AddHandler client.DownloadFileCompleted, AddressOf client_DownloadCompleted
client.DownloadFileAsync(New Uri("SomeURL"), "SomePlaceOnHardDrive")
btnStartDownload.Text = "Download in Progress"
btnStartDownload.Enabled = False
End Sub
In the previous code, we are creating two event handlers to handle when the Progress of the file download changes, and when the download completes.
We also use the DownloadFileAsync method so that the download(which could be lengthy) does not freeze the main GUI.
Next, we need to do the code to calculate the percentage of the download complete so that we can assign it to the ProgressBar.
Private Sub client_ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
Dim bytesIn As Double = Double.Parse(e.BytesReceived.ToString())
Dim totalBytes As Double = Double.Parse(e.TotalBytesToReceive.ToString())
Dim percentage As Double = bytesIn / totalBytes * 100
progressBar.Value = Int32.Parse(Math.Truncate(percentage).ToString())
End Sub
In this code, we use the BytesReceived and TotalBytesToReceive properties of the DownloadProgressChangedEventArgs object.
Next, we need to do the code for the event when the download completes.
Private Sub client_DownloadCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
MessageBox.Show("Download Complete")
btnStartDownload.Text = "Start Download"
btnStartDownload.Enabled = True
End Sub
If you would like to have the percentage "embedded" into the ProgressBar, check out JacobJordan's tutorial here, http://www.dreaminco...wtopic94631.htm





MultiQuote






|