Ebikeneser
Ebikeneser

Reputation: 2364

Wait for webBrowser control to fully load

I am currently working with a webBrowser control in a WinForm -

public Form1()
        {
            InitializeComponent();

            webBrowser1.AllowNavigation = true;
            webBrowser1.Navigate("http://foo.bar");        
        }

I have a button control that takes the webBrowser1.Url.OriginalString and sets it to a textBox -

// On button_Click
string requestResponse = webBrowser1.Url.OriginalString;
requestURLtextBox.Text = requestResponse;

However if the button is clicked before webBrowser1 has had enough time to get the OriginalString text, this will error as the value does not exist yet.

I tried adding -

while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
      Thread.Sleep(1000);  
}

Before the previous code in the button_Click event however this went into an infinite loop. How can I retrieve the OriginalString after the webBrowser is complete?

Upvotes: 0

Views: 1965

Answers (1)

rheitzman
rheitzman

Reputation: 2297

Here some VB simple code that may work for you:

    If mbBusy Then Exit Function ' form level variable
    mbBusy = True
    Web.Navigate("http://.....htm")
    dtWebWait = Now().AddSeconds(timeoutSeconds)
    Do Until Web.ReadyState = WebBrowserReadyState.Complete
        Application.DoEvents()
        If Now() > dtWebWait Then
            MsgBox("navigate timeout - search form")
            Exit Function
        End If
        Threading.Thread.Sleep(250)
    Loop
    mbBusy = False

Upvotes: 1

Related Questions