user3080392 user3080392 - 4 months ago 24
Vb.net Question

Open multiple URLs successively in WebBrowser control in VB.NET

I'm trying to make a "rotator" on a form that cycles through a series of urls and displays the url in the

WebBrowser
control. The following code displays my form, but the form remains white/blank and then the last url in the array appears after a while. When I put a
MessageBox
in-between each url, to create a stop, it works and each url appears. I've tried putting a
Sleep
in place of the
MessageBox
, but that didn't work. I've also tried increasing the
Sleep
time, but that didn't work either. How can I make it work correctly?

Sub Rotate()

Dim Urls() As String = {"www.stackoverflow.com", "www.google.com", "www.yahoo.com"}
Dim counter As Integer = 0

Form3.Show()

Do Until counter = 3

Form3.WebBrowser1.ScriptErrorsSuppressed = True
Form3.WebBrowser1.Navigate(Urls(counter))
'MessageBox.Show("Next")
counter = counter + 1
System.Threading.Thread.Sleep(2000)

Loop

End Sub

Answer

You can call Application.DoEvents after changing the URL so that the control gets the chance to redraw itself.
However, a better approach would be to use a timer which fires every 2 seconds and then change the URL in the event handler so that your UI keeps responsive.
For example setup a new field myTimer in your form, init it in your form's loading event and in the Tick event you call your Rotate method. As Rotate is now called several times, we have to move the counter variable out of the method and make it a field so that we keep its value between the invocations. I usually write C# so hopefully I did not make some typos below :)

Private WithEvents myTimer As System.Windows.Forms.Timer
Private counter As Integer

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    ' ... your existing code ...
    counter = 0
    myTimer = New System.Windows.Forms.Timer
    myTimer.Interval = 2000
    myTimer.Enabled = True
    myTimer.Start()
End Sub

Private Sub myTimerTick() Handles myTimer.Tick
    Rotate()
End Sub

Sub Rotate()
    Dim Urls() As String = {"www.stackoverflow.com", "www.google.com", "www.yahoo.com"}
    WebBrowser1.ScriptErrorsSuppressed = True
    WebBrowser1.Navigate(Urls(counter))           
    counter = counter + 1
    If counter > 3 Then myTimer.Stop()
End Sub
Comments