C#WebBrowser controls the use of tutorials and collection techniques - Su Fei co

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

C#WebBrowser controls the use of tutorials and collection techniques - Su Fei collection

Have a look first to the commonly used method

Navigate(string urlString):Browse the urlString representation.
Navigate(System.Uri url): Browse the URL representation.
Navigate(string urlString, string targetFrameName, byte[] postData, string additionalHeaders): Browse the urlString representation of the web site, and send messages in postData
//(When we usually visit a site the user name and password as the postData sent)
GoBack(): Back off
GoForward(): Forward
Refresh(): Refresh
Stop(): Stop it
GoHome(): Home page
Common property of the WebBrowser control: 

Document: Gets the current browsing documents
DocumentTitle: Gets the current webpage title
StatusText: Gets the current status bar text
Url: Gets the current browsing web site Uri
ReadyState: Gets the browse state
Common control's WebBrowser event: 
DocumentTitleChanged,
CanGoBackChanged,
CanGoForwardChanged,
DocumentTitleChanged,
ProgressChanged,
ProgressChanged
After the DocumentCompleted page finishes loading events
Access to Cookie

General browsing copy code

      [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
            static extern bool InternetGetCookieEx(string pchUrl, string pchCookieName, StringBuilder pchCookieData, 

ref System.UInt32 pcchCookieData, int dwFlags, IntPtr lpReserved); private static string GetCookieString(string url) { uint datasize = 1024; StringBuilder cookieData = new StringBuilder((int)datasize); if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x2000, IntPtr.Zero)) { if (datasize <0) return null; cookieData = new StringBuilder((int)datasize); if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, IntPtr.Zero)) return null; } return cookieData.ToString(); } private void webBrowser1_DocumentCompleted_1(object sender, WebBrowserDocumentCompletedEventArgs e) { richTextBox1.Text = string.Empty; if (cbcookie.Checked) { if (checkBox1.Checked) { richTextBox1.Text = GetCookieString(textBox1.Text.Trim()); } else { richTextBox1.Text = webBrowser1.Document.Cookie; } } }

How to set the agent.

In the completion of the loading. How a page after the execution of the code

//This event is only executed when the completion of the loading of the current page
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //E.Url is currently loading page, 
            if (e.Url.ToString().Contains("http://sufeinet.com"))
            {
                //Perform the operation 1
            }
            else if (e.Url.ToString().Contains("http://baidu.com"))
            {
                //Perform the operation 2
            }
        }

How open the webpage is prohibited. In a new window

            private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
            {
                if (cbwindownew.Checked)
                {
                    string url = ((System.Windows.Forms.WebBrowser)sender).StatusText;
                    webBrowser1.Navigate(url);
                    e.Cancel = true;
                }
            }

1,Gets the value of the control non input:

webBrowser1.Document.All["Control ID"].InnerText;
Or webBrowser1.Document.GetElementById("Control ID").InnerText;
Or webBrowser1.Document.GetElementById("Control ID").GetAttribute("value");

2 gets the value of the input control:

webBrowser1.Document.All["Control ID"].GetAttribute("value");;
Or webBrowser1.Document.GetElementById("Control ID").GetAttribute("value");

3,To the input frame assignment:

    //Input box
    user.InnerText = "myname";
    password.InnerText = "123456";
    webBrowser1.Document.GetElementById("password").SetAttribute("value", "Welcome123");

4,The drop-down, check, check:

    //The drop-down box: 
    secret.SetAttribute("value", "question1");  
    //Check box
    rememberme.SetAttribute("Checked", "True");
    //Checkbox
    cookietime.SetAttribute("checked", "checked");

5,According to the operation is known to have ID element has no ID elements:

HtmlElement btnDelete = webBrowser1.Document.GetElementById(passengerId).Parent.Parent.Parent.Parent.FirstChild.FirstChild.Children[1].FirstChild.FirstChild;

According to Parent, FirstChild, Children[1] array, how many levels of elements can be found.

6,Gets a Div or other elements of style:

webBrowser1.Document.GetElementById("addDiv").Style;

7,Direct execution of the script function page, with dynamic parameters or with no parameters.:

Object[] objArray = new Object[1];
objArray[0] = (Object)this.labFlightNumber.Text;
webBrowser1.Document.InvokeScript("ticketbook", objArray);
webBrowser1.Document.InvokeScript("return false");

8,Automatic click, automatic submission:

HtmlElement btnAdd = doc.GetElementById("addDiv").FirstChild;
btnAdd.InvokeMember("Click");

9,Automatic assignment, and then click the submit button when the script error or have been loaded, generally is the click event execution too fast, then need to use Timer controls to delay the submit button events:

this.timer1.Enabled = true;
this.timer1.Interval = 1000 * 2;
private void timer1_Tick(object sender, EventArgs e)
{
    this.timer1.Enabled = false;
    ClickBtn.InvokeMember("Click");//Execution button operation
}

10,Shielding script error:

The WebBrowser control ScriptErrorsSuppressed is set to True.

11,Automatic click pop-up boxes:

private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
  //Automatic click confirm or pop-up hints
  IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument;
  vDocument.parentWindow.execScript("function confirm(str){return true;} ", "javascript"); //Confirmation Popup
  vDocument.parentWindow.execScript("function alert(str){return true;} ", "javaScript");//Popup
}

12.WebBrowser after the page has finished loading, automatic click when some automation pop-up box on the page (shield)

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        //Automatic click confirm or pop-up hints
        IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument;
        vDocument.parentWindow.execScript("function confirm(str){return true;} ", "javascript"); //Confirmation Popup
        vDocument.parentWindow.execScript("function alert(str){return true;} ", "javaScript");//Popup
        //Here is your execution operation code
    }

13,Gets the webpage in Iframe, and set the Iframe SRC

HtmlDocument docFrame = webBrowser1.Document.Window.Frames["mainFrame"].Document; 
Or
HtmlDocument docFrame = webBrowser1.Document.All.Frames["mainFrame"].Document; 
docFrame.All["mainFrame"].SetAttribute("src", "http://www.sufeinet.com/");

Webpage in the presence of Iframe webBrowser1.Url and webBrowser1_DocumentCompleted e.Url not the same, the former is the main framework of Url, which is the current active frame in Url.

14,For the control focus

this.webBrowser1.Select();
this.webBrowser1.Focus();
doc.All["TPL_password_1"].Focus();

15,Open the webpage files

webBrowser1.Navigate(Application.StartupPath + @"\Test.html");

16,Get the element, form

    //According to the Name element
    public HtmlElement GetElement_Name(WebBrowser wb,string Name)
    {
        HtmlElement e = wb.Document.All[Name];
        return e;
    }
    //According to the Id element
    public HtmlElement GetElement_Id(WebBrowser wb, string id)
    {
        HtmlElement e = wb.Document.GetElementById(id);
        return e;
    }
    //According to the Index element
    public HtmlElement GetElement_Index(WebBrowser wb,int index)
    {
        HtmlElement e = wb.Document.All[index];
        return e;
    }
    //Form form name, return form
    public HtmlElement GetElement_Form(WebBrowser wb,string form_name)
    {
        HtmlElement e = wb.Document.Forms[form_name];
        return e;
    }
    //The value of the value property setting elements
    public void Write_value(HtmlElement e,string value)
    {
        e.SetAttribute("value", value);
    }
    //Executive element method, such as: click, submit (Form form names).
    public void Btn_click(HtmlElement e,string s)
    {
        e.InvokeMember(s);
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Perry at November 14, 2013 - 7:39 AM