Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submission of a webpage form using WebBrowser control in C#

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.

like image 553
vikramjb Avatar asked Feb 04 '11 19:02

vikramjb


1 Answers

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.

like image 120
John Koerner Avatar answered Oct 25 '22 20:10

John Koerner