You don't need any async
procedure here. The WebBrowser.DocumentCompleted event is already invoked asynchronously. DoEvents()
is equally useless if not disruptive.
You just need to subscribe to the DocumentCompleted
event and call the Navigate
method to let the WebBrowser load the remote Html resource.
When the HtmlDocument
is finally loaded, the WebBrowser will signal its completion setting its state to WebBrowserReadyState.Complete
.
About the Html Input Element and Forms:
here, the code is supposing that there's only one Form in that HtmlDocument.
It may be so, but it may be not. A Html Document can have more than one Form and each Frame can have its own Document. IFrames will have one each for sure.
Read the notes in this answer (C# code, but you just need the notes) for more information on how to handle multiple Frames/IFrames
Button1
will wire up the DocumentCompleted
event and call Navigate()
.
When the Document is completed, the code in the event handler will run and perform the LogIn procedure.
The event handler is then removed, since it has complelted its task and you still need to use the WebBrowser for other purposes.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
WebSiteLogIn()
End Sub
Private Sub WebSiteLogIn()
AddHandler WebBrowser1.DocumentCompleted, AddressOf PageWaiter
WebBrowser1.Navigate("https://thesite.com/#/login")
End Sub
Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
WebBrowser1.Document.GetElementById("username").SetAttribute("value", "Username")
WebBrowser1.Document.GetElementById("Password").SetAttribute("value", "Password")
Dim allInputElements = WebBrowser1.Document.Body.All.
Cast(Of HtmlElement).Where(Function(h) h.TagName.Equals("INPUT")).ToList()
For Each element As HtmlElement In allInputElements
If element.GetAttribute("type").ToUpper().Equals("SUBMIT") Then
element.InvokeMember("click")
End If
Next
RemoveHandler WebBrowser1.DocumentCompleted, AddressOf PageWaiter
Button1.Enabled = True
End If
End Sub
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…