Submission of a webpage form using WebBrowser cont

2019-04-08 02:21发布

问题:

I have seen a lot of posts regarding this particular subject on SO as well as on the web in general and most if not all code is as seen 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 whatsoever but for the life its not submitting. The sample page that I am using has simple button, what it does, it alerts the selection of the radio button and then submits the form. For some strange reason when the form is submitted via code using the WebBrowser control, the form is submitted but the alert never shows up.

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

回答1:

Would performing a click on the button do what you need it to do? You will need to add a COM reference to the Microsoft HTML Object Library (which you may already have). For example, if you load up google into the webbrowser control, this code will place "hello world" into the search box and perform the 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 throws a script error from google, but that appears to be a timing issue based on some of the ajax calls google has on the home page.



回答2:

To fix your problem you need to replace line:

form.submit();

With 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 alert about user selection and submit form.



回答3:

I've got a more dirty one-liner working by injecting a JavaScript to submit the form

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

That's been working for me when interacting with a site using a lot of JavaScript and button beyond the form.