Příklad jednoduchého stahovacího programu: Prvky: - ProgressBar1 - klasický progressbar ukazující postup procesu - TextBox1 - textbox obsahující URL stahovaného souboru - Button1 - tlačítko Stáhnout - Label2 - ukazuje rychlost stahování - Label4 - ukazuje zbývající čas - Timer1 - interval 1 sekunda - disabled Kód (musí být uvnitř nějaké třídy):
Dim WithEvents webcl As New WebClient()
Dim minule As Long
Dim stazeno As Long
Dim celkem As Long
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Timer1.Start()
If Not IO.Directory.Exists(Application.StartupPath + "\Staženo") Then IO.Directory.CreateDirectory(Application.StartupPath + "\Staženo")
webcl.DownloadFileAsync(New Uri(TextBox1.Text), Application.StartupPath + "\Staženo\" + IO.Path.GetFileName(TextBox1.Text))
Catch ex As Exception : MsgBox("Nelze stáhnout soubor" + ControlChars.NewLine + ex.ToString, MsgBoxStyle.Exclamation, "Chyba")
End Try
End Sub
Private Sub webcl_DownloadFileCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) Handles webcl.DownloadFileCompleted
Timer1.Stop()
ProgressBar1.Value = 0
Label2.Text = ""
Label4.Text = ""
MsgBox("Stahování dokončeno", MsgBoxStyle.Information, "Informace")
End Sub
Private Sub webcl_DownloadProgressChanged(ByVal sender As Object, ByVal e As System.Net.DownloadProgressChangedEventArgs) Handles webcl.DownloadProgressChanged
stazeno = e.BytesReceived
celkem = e.TotalBytesToReceive
ProgressBar1.Value = e.ProgressPercentage
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim navic As Long = (stazeno / 1024) - (minule / 1024)
Dim zbyva As Long = (celkem / 1024) - (stazeno / 1024)
Dim tspan As TimeSpan = TimeSpan.FromSeconds(zbyva / navic)
Label2.Text = navic.ToString + " kB/s"
Label4.Text = Math.Floor(tspan.TotalHours).ToString + ":" + Microsoft.VisualBasic.Right("00" + tspan.Minutes.ToString, 2) + ":" + Microsoft.VisualBasic.Right("00" + tspan.Seconds.ToString, 2)
minule = stazeno
End Sub
|