Windows Form Application - Manipulating Input Elements in WinForm WebBrowser
Although I am familiar with the HttpWebResponse
/ HttpWebRequest
for entering the site, I tried it now using the mshtml library and found some strange behavior, and I would like to know if someone else can help me here ..
I have an HTML login page with a java database with Username
field, Password
field and Button
.
The logic is very simple, I have a built-in winform application with a built-in web browser. In the Document_Completed
event, I use the following code to enter my settings and click a 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 { } } }
Besides the fact that this code is very fast and without error handling, it should do the trick, and this happens partially.
There are two scenarios:
I run the tool, it loads a web page.
- The tool fills in the UserID field and Password field correctly
- Tool cannot press button
I press the button manually, I logged in, I log out, I returned to the login page
- I immediately logged in again, the tool enters information
- The tool immediately presses the button.
Is there anyone who could explain to me why this is happening and how I could get around this with the current setting (hence not using HttpWebRequest
). I donβt see the difference between loading the page at startup or redirecting after logging out, but apparently there is a difference there, or I'm doing something wrong.
Any feedback on this is greatly appreciated.
Thanks Kevin
EDIT:
I added a Button
to my Windows Form, which is based on the same base code as below, to click a button on a web page, this works fine.
I clicked this button in the webBrowser_Completed
event, but it does not work. For some reason, everything I add to the webBrowser_DocumentCompleted
event webBrowser_DocumentCompleted
not allow the click event to be webBrowser_DocumentCompleted
for a button in a WebBrowser
. As soon as this whole event ends, if I then try to fire it, it will work, but I would like to automate this. Any tips?