我想限制等待Webbrowser加载; 我开始使用下面的代码,等待Webbrowser在开始下一个操作之前加载; 我希望等待限制为60秒,如果网页没有加载,则代码将执行下一个操作; 任何帮助表示赞赏:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
WebBrowser1.Navigate("www.mekdam.com")
While WebBrowser1.ReadyState <> WebBrowserReadyState.Complete
Application.DoEvents()
End While
End Sub
End Class
由于
答案 0 :(得分:1)
您应该检查ReadyState
事件中的DocumentCompleted
。这样它就不会挂起您的应用程序。
如果添加计时器,可以取消加载页面,如果花费的时间太长:
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
WebBrowser1.Navigate("http://www.msn.co.uk")
Timer1.Interval = 2000
Timer1.Enabled = True
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
'If the timer is not running then we are not waiting for the document to complete
If Not Timer1.Enabled Then Exit Sub
'Check the document that just loaded is the main document page (not a frame) and that the control is in the ready state
If e.Url.AbsolutePath = CType(sender, WebBrowser).Url.AbsolutePath AndAlso WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
'we loaded the page before the timer elapsed
Timer1.Enabled = False
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'timer has elapsed so cancel page load
WebBrowser1.Stop()
'Disable the timer
Timer1.Enabled = False
End Sub
答案 1 :(得分:-1)
Dim secondTime As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("http://www.msn.co.uk")
Timer1.Interval = 100
Timer1.Enabled = True
secondTime = False
Timer1.Start()
End Sub
Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
If e.Url.AbsolutePath = CType(sender, WebBrowser).Url.AbsolutePath AndAlso WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
'loading completed before the timer elapsed
Timer1.Enabled = False
Timer1.Stop()
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'timer we cancle the loading as it takes long time
If secondTime = True Then
WebBrowser1.Stop() 'Second time call
Else
secondTime = True 'First time call
End If
End Sub
如果对象Timer1
设置为Enabled
或Time1.Start()
,则会调用Timer1.Tick
函数。因此,将阻止页面在开始时加载。为了防止在时间转义之前加载中出现意外停止,我们使用变量secondTime
来确保第二次调用或转义给定时间。确认我们使用IF
比较并准备好在第二次调用或在给定间隔之后获得中止调用。 Timer1.Tick
内的条件确保了。