I am trying to learn more about event handling. I tried writing the code below but it doesn't seem to be working for some reason. What I am trying to do is navigating to a url, wait until its loaded and then run the msgbox.
Any idea what I'm doing wrong?
Private Shared event_1 As New AutoResetEvent(False)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
WebBrowser1.Navigate("http://google.com")
AddHandler WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf wb)
event_1.WaitOne()
MsgBox("The page is finished loading ")
End Sub
Private Sub wb(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
If e.Url.AbsolutePath <> TryCast(sender, WebBrowser).Url.AbsolutePath Then
Return
End If
event_1.Set()
End Sub
You can just catch the DocumentCompleted event on the WebBrowser1 object like this:
Private Sub webBrowser1_DocumentCompleted(ByVal sender As Object, _
ByVal e As WebBrowserDocumentCompletedEventArgs) _
Handles webBrowser1.DocumentCompleted
MsgBox("THe page is loaded")
End Sub
See samples here: http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
When you issue the event_1.WaitOne()
, the main thread is blocked. And that includes the WebBrowser. Therefore the event_1.Set()
will never get executed.
However, you can achieve the same behavior with a different method. Not using event whatsoever.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Enabled = False ' if you realy want to block the UI as well
WebBrowser1.Navigate("http://www.google.com")
Do
Application.DoEvents()
Loop Until WebBrowser1.ReadyState = WebBrowserReadyState.Complete
MsgBox("The page is finished loading ")
Me.Enabled = True ' re-enable the UI
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.