user3080392 user3080392 - 1 year ago 59 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

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
in-between each url, to create a stop, it works and each url appears. I've tried putting a
in place of the
, but that didn't work. I've also tried increasing the
time, but that didn't work either. How can I make it work correctly?

Sub Rotate()

Dim Urls() As String = {"", "", ""}
Dim counter As Integer = 0


Do Until counter = 3

Form3.WebBrowser1.ScriptErrorsSuppressed = True
counter = counter + 1


End Sub


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
End Sub

Private Sub myTimerTick() Handles myTimer.Tick
End Sub

Sub Rotate()
    Dim Urls() As String = {"", "", ""}
    WebBrowser1.ScriptErrorsSuppressed = True
    counter = counter + 1
    If counter > 3 Then myTimer.Stop()
End Sub