Representing a web page form using a WebBrowser control in C #

I saw a lot of posts on this particular subject about SO, and also on the Internet in general, and most, if not all of the code, as shown below.

private void btnSubmit_Click(object sender, RoutedEventArgs e) { webBrowser1.Navigate(new Uri("http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/onsubmit.htm")); } private void btnLogin_Click(object sender, RoutedEventArgs e) { mshtml.HTMLDocument htmlDoc = null; htmlDoc = (mshtml.HTMLDocument) this.webBrowser1.Document; if (webBrowser1.Document != null) { foreach (mshtml.HTMLFormElement form in htmlDoc.forms) { form.submit(); break; } } } 

The code has no errors, except for the whole life that it does not send. The example page that I use has a simple button, what does it do, it warns the radio button selection, and then submits the form. For some strange reason, when a form is submitted via code using the WebBrowser control, the form is submitted, but the warning never appears.

I'm not sure what I'm doing wrong here. Any help on this would be appreciated.

+6
c # controls wpf-controls webbrowser-control
source share
3 answers

Doing a click on a button do what you need? You will need to add the COM link to the Microsoft HTML object library (which you already have). For example, if you load google into a webbrowser control, this code will put "hello world" in the search field and search:

  mshtml.IHTMLDocument2 doc = ((mshtml.HTMLDocumentClass)webBrowser1.Document); ((mshtml.IHTMLElement)doc.all.item("q")).setAttribute("value", "hello world"); MessageBox.Show("Clicking I'm feeling lucky button"); ((mshtml.HTMLInputElement)doc.all.item("btnI")).click(); 

Edit: I updated the code for the components that the WPF WebBrowser control uses. Also note that this sometimes causes a script error from google, but this is apparently a synchronization problem based on some ajax calls that google has on the home page.

+6
source share

To fix the problem, you need to replace the line:

 form.submit(); 

With the following code:

 var children = form as IEnumerable; var inputs = children.OfType<mshtml.HTMLInputElement>(); var submitButton = inputs.First(i => i.type == "submit"); submitButton.click(); 

This will show a warning about the user selection and the submission form.

+4
source share

I have a messier single line liner that works by injecting JavaScript to submit the form

 _webBrowser.InvokeScript("eval", new object[] { "document.getElementById('formName').submit()" }); 

This worked for me when interacting with the site using a lot of JavaScript and buttons outside the form.

+1
source share

All Articles