If you want to create a simple downloader or you want to learn the concept of background worker and progress bar , you must go through this basic article.
Here we are using a very simple example that will help you to understand these concepts. So we shall go steps by step.
- First of all add a button to your Form to start download, a progress bar to show download progress and a background worker for background processing of download. A cancel download button is additional.
- Set the following properties of background worker: Put below code on the load event of form or the same you can set in the properties panel of the background worker.
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.WorkerSupportsCancellation = True
- Define an object "wc" of class "webclient" for download/upload operation. Here WithEvents is supporting handling of progress/completion of download.
Dim WithEvents wc As New WebClient
It needs following imports: Add it as the first line of the code.
- Now double click on the background worker to go to the code and add below code. Here we shall add the actual code that we want the background worker to perform.
- Also add event handlers at the load event of forms as below:
AddHandler object as event, object as delegate.
AddHandler wc.DownloadProgressChanged, AddressOf wc_DownloadProgressChanged
AddHandler wc.DownloadFileCompleted, AddressOf wc_DownloadFileCompleted
- Now add the following two methods i.e. wc_DownloadProgressChanged and wc_DownloadFileCompleted to monitor the status of download progress and completion (each containing only one line of code).
Private Sub wc_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs) Handles wc.DownloadProgressChanged
ProgressBar1.Value = e.ProgressPercentage
' to update progress bar with the current progress percetage.
Private Sub wc_DownloadFileCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
'On completion of download, you can add a message like this.
- Now double click the "Start download" button to add code to start downloading and just add one line:
- Now try to run the program. You may get following error:
- To overcome this error just add following line at the load event of the form.
Control.CheckForIllegalCrossThreadCalls = False
- Now run the program again. That's It your downlaoder is working with the progress shown by progress bar!!
And now download completed:
- On the "Cancel Download" button you can add below code to cancel download operation in between.
So this is quite simple. Please raise questions concerned or comment on it.
Get the source code here.