Submission of a webpage form using WebBrowser control in C#

六眼飞鱼酱① 提交于 2019-12-04 06:33:47

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!