1

How can I run some stuff in a subroutine only when a specific URL has been completely loaded in a vb.net webbrowser.

e.g.

sub button click

webbrowsernavigate to whatever

(This is what I need)if document has loaded statement
do stuff

end sub

Thanks

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Ben Holden Crowther
  • 109
  • 2
  • 5
  • 11
  • Are you looking for [tag:vba] or [tag:vb.net]? – enderland Sep 05 '13 at 18:38
  • You could use `async/await` for this if targeting .NET 4.5. I don't have a VB.NET sample ready, but [here's how](http://stackoverflow.com/a/18573522/1768303) to do it in C#. – noseratio Sep 05 '13 at 22:10

1 Answers1

1

The WebBrowser class has a DocumentCompleted event that you can bind to:

Occurs when the WebBrowser control finishes loading a document.

The MSDN article has an example which demonstrates how you can use this event effectively:

Private Sub PrintHelpPage()

    ' Create a WebBrowser instance.  
    Dim webBrowserForPrinting As New WebBrowser()

    ' Add an event handler that prints the document after it loads. 
    AddHandler webBrowserForPrinting.DocumentCompleted, New _
        WebBrowserDocumentCompletedEventHandler(AddressOf PrintDocument)

    ' Set the Url property to load the document.
    webBrowserForPrinting.Url = New Uri("\\myshare\help.html")

End Sub 

Private Sub PrintDocument(ByVal sender As Object, _
    ByVal e As WebBrowserDocumentCompletedEventArgs)

    Dim webBrowserForPrinting As WebBrowser = CType(sender, WebBrowser)

    ' Print the document now that it is fully loaded.
    webBrowserForPrinting.Print()
    MessageBox.Show("print")

    ' Dispose the WebBrowser now that the task is complete. 
    webBrowserForPrinting.Dispose()

End Sub
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • Hi, Is there any way to do it in a similar way to the code in my question? – Ben Holden Crowther Sep 05 '13 at 19:17
  • @BenHoldenCrowther Probably but I wouldn't recommend it. The `WebBrowser` control is asynchronous, so it won't block the UI while it's loading. Using events like this is a *much* more elegant way of handling it that simply blocking the whole application while you wait for a document to download. – p.s.w.g Sep 05 '13 at 19:22
  • Do you know of a way to do it in a similar way to in my question? I would really appreciate it. – Ben Holden Crowther Sep 05 '13 at 19:50
  • the webbbrowser control raises BeforeNavigate2 and other events from a background thread. If those events are blocked by your waiting code, the navigation won't happen. – Sheng Jiang 蒋晟 Sep 06 '13 at 01:05