第一次单击按钮时出现问题,webbrowser.DocumentText始终未加载,但在第二次或第三次点击时,始终会加载documentText。
如果有人可以提供建议,我很高兴。
我的代码如下:
Private Property pageready As Boolean = False
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button3.Click
WebBrowser1.Navigate(url)
WaitForPageLoad()
RichTextBox1.Text = WebBrowser1.DocumentText
Msgbox ("Document Loaded")
End Sub
Private Sub WaitForPageLoad()
AddHandler WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
While Not pageready
Application.DoEvents()
End While
pageready = False
End Sub
Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
pageready = True
RemoveHandler WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
End If
End Sub
答案 0 :(得分:1)
任务延迟,直到加载DocumentComplete对我来说是一种困扰。
Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button3.Click
WebBrowser1.Navigate(url)
Await ExampleMethodAsync()
RichTextBox1.Text = WebBrowser1.DocumentText
Msgbox ("Document Loaded")
End Sub
Async Function ExampleMethodAsync() As Task
' The following line simulates a task-returning asynchronous process.
Await Task.Delay(1750)
End Function
答案 1 :(得分:0)
您可以通过以下两种方式动态等待WebBrowser
加载整个页面:
将Async/Await
方法扩展为实际等待页面加载,您可以使用ManualResetEvent
。 MRE可用作门:当您致电Set()
时,您打开门,当您拨打Reset()
时关闭它,当您拨打WaitOne(-1)
时,您在门口等待它打开(如果它已关闭)。
Private DocumentCompletedResetEvent As New ManualResetEvent(False)
Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button3.Click
WebBrowser1.Navigate(url)
Await ExampleMethodAsync()
RichTextBox1.Text = WebBrowser1.DocumentText
Msgbox("Document Loaded")
End Sub
Async Function ExampleMethodAsync() As Task
DocumentCompletedResetEvent.Reset() 'Makes sure that the MRE is closed.
DocumentCompletedResetEvent.WaitOne(-1) 'Waits for it to open.
End Function
Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
DocumentCompletedResetEvent.Set() 'Opens the MRE.
End If
End Sub
第二种方法为DocumentCompleted
事件添加临时事件处理程序。使用Lambda expressions,您可以为事件处理程序创建一个内联方法。
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
WebBrowser1.Navigate(TextBox1.Text)
'Creates a temporary event handler.
Dim DocumentCompletedHandler As WebBrowserDocumentCompletedEventHandler = _
Sub()
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
RemoveHandler WebBrowser1.DocumentCompleted, DocumentCompletedHandler 'Removes the temporary event handler.
RichTextBox1.Text = WebBrowser1.DocumentText
Msgbox("Document Loaded")
End If
End Sub
AddHandler WebBrowser1.DocumentCompleted, DocumentCompletedHandler 'Adds the temporary event handler.
End Sub