Windows Form Application – Manipulating input-elements in WinForm WebBrowser
Although I am familiar with HttpWebResponse
/HttpWebRequest
to login to a website, I was trying it now via using the mshtml library and found some weird behavior and I would like to see if someone else might be able to help me out here..
I have an HTML login page with a java backend with a Username
field, a Password
field and a Button
.
The logic is very basic, I have a built a winform app with a built in webbrowser.
At the Document_Completed
event I use the following code to enter my settings and to click the button.
private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser.Url.ToString() == @"MyWebPage/signin")
{
HTMLDocument hdc = new HTMLDocumentClass();
hdc = (HTMLDocument)webBrowser.Document.DomDocument;
IHTMLElement elb = hdc.getElementById("login_button");
IHTMLInputElement elu = (IHTMLInputElement)hdc.getElementById("username");
IHTMLInputElement elp = (IHTMLInputElement)hdc.getElementById("password");
try
{
elu.value = "MyID";
elp.value = "MyPwd";
elb.click();
}
catch { }
}
}
Apart for this code being very quick and without error handling, it should do the trick and it does, partially..
There are two scenario's:
I launch the tool, it loads the webpage.
I click the button manually, I am logged in, I click logout, I am back at login page
Is there anyone who might be able to explain me why this happens and how I could get around this with the current setup (hence not using HttpWebRequest
). I don't see the difference between loading the page at startup or being redirected after logout, but apparently there is a difference in there or I am doing something wrong.
Any feedback on this matter is very much appreciated.
Thanks, Kevin
I added a Button
to my Windows Form that bas the same backend Code as below in order to click the button on the webpage, this works perfectly.
I triggered clicking this button in the webBrowser_Completed
event but it doesn't work.
For some reason, everything I add to the webBrowser_DocumentCompleted
event does not allow me to trigger the click event for the button in my WebBrowser
control. Once that entire event has completed, if I then try to trigger it it works but I would like to automate this.. Any advice?
This might be a long shot and not the most elegant workaround but how about letting a backgroundworker run for a second in your DocumentCompleted event that then triggers the button that you clicked from it's seperate thread. This might just get this automated. As this will run from a different thread, keep in mind that you might have to invoke certain controls so this might be another downside to this workaround..
If this doesn't work then, as Regfor previously suggested, Watin.org can help you out.