C#webbrowser control using tutorials and tips for collecting

Source: Internet
Author: User
Tags control label

Common Properties and methods

Navigate (String urlstring): Browse urlstring represents the URL Navigate (system.uri URL): Browse the URL represented by Navigate (string urlstring, String Targetframename, byte[] postdata, String additionalheaders): Browse the URL represented by urlstring and send the message in PostData// (Usually when we log on to a website, we will send the username and password as postdata) GoBack (): Back GoForward (): Forward refresh (): Refresh Stop (): Stop GoHome () : Browse the Home page WebBrowser control's Common properties: Document: Get the currently browsing documents Documenttitle: Gets the page title currently being browsed StatusText: Gets the text URL of the current status bar: Gets the urireadystate of the URL currently being browsed: Gets the status of the browse WebBrowser common events for the control: documenttitlechanged,cangobackchanged,cangoforwardchanged,documenttitlechanged, Progresschanged,progresschangeddocumentcompleted event replication Code after page load is complete

1. Gets the value of the non-input control:

webbrowser1.document.all["Control ID"]. InnerText; or webBrowser1.Document.GetElementById ("Control ID"). InnerText; or webBrowser1.Document.GetElementById ("Control ID"). GetAttribute ("value");      WebBrowser_GrabCoupon.Document.GetElementsByTagName ("Control label"). Getelementsbyname (the Name property of the control) [0]. GetAttribute ("style");    Get elements from tags

2. Get the value of the input control:

webbrowser1.document.all["Control ID"]. GetAttribute ("value"), or WebBrowser1.Document.GetElementById ("Control ID"). GetAttribute ("value");

3. Assign values to the input box:

Input box user. InnerText = "MyName";p assword. InnerText = "123456"; WebBrowser1.Document.GetElementById ("Password"). SetAttribute ("Value", "Welcome123");

4, pull down, check, multi-select:

Drop-down box: Secret. SetAttribute ("Value", "Question1"); check box rememberme. SetAttribute ("Checked", "True");//multi-marquee cookietime. SetAttribute ("Checked", "checked");

5. Manipulate elements without IDs based on elements known to have an ID:

HtmlElement btndelete = webBrowser1.Document.GetElementById (Passengerid). PARENT.PARENT.PARENT.PARENT.FIRSTCHILD.FIRSTCHILD.CHILDREN[1]. Firstchild.firstchild;

6. Get the style of div or other elements:

WebBrowser1.Document.GetElementById ("Adddiv"). Style;

7, directly execute the script function in the page, with dynamic parameters or without parameters are the line :

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 the problem is always loaded, the Click event is usually executed too fast, you need to use the Timer control or application.doevents () delay the execution of the Submit button event:

this.timer1.Enabled = True;this.timer1.interval = $ * 2;private void Timer1_Tick (object sender, EventArgs e) {This    . timer1. Enabled = false;    Clickbtn.invokemember ("click");//Perform a push-button operation}
private void Delayclick () {    ///The following code indicates a delay of 1 seconds to perform the click operation, and will not be like Thread.Sleep (1000) will cause the program to suspend death, but the efficiency will be reduced    DateTime time = DateTime.Now;    while (time. AddSeconds (1) >= DateTime.Now)    {        application.doevents ();    }    Clickbtn.invokemember ("click");//Perform a push-button operation}

Add: The Role of Application.doevents () in C #

Summary in Visual Studio: processes all Windows messages currently in Message Queuing.
Hand over the CPU control so that the system can process all Windows messages in the queue, such as in a large computation cycle, Adding application.doevents can prevent the interface from stopping responding because the WinForm message loop is a thread to handle, so if one of your operations is time-consuming, the message is processed so that you can continue with the time-consuming operation, and the Application.doevents method is to allow you It is called inside the time-consuming operation, and the message in the message queue is processed. Like a mouse mouse click is a Windows message, if the time-consuming operation has been done, then the interface is like a deadlock. It is important to note that the use of application.doevents also reduces program performance

(Application.doevents used more in processing time-consuming operations)

10. Masking script Error:

Set the WebBrowser control scripterrorssuppressed to True

11. Automatically click the popup box: Use IHTMLDocument2 to add a reference to the Microsoft HTML Object Library:

(If you do not have a Microsoft HTML Object Library, you will first add COM components, browse for file introduction Microsoft.mshtml.dll, file address is C:\WINDOWS\system32\mshtml.dll)

private void Webbrowser1_navigated (object sender, WebBrowserNavigatedEventArgs e) {  //auto-click Popup Confirmation or popup prompt  IHTMLDocument2 vdocument = (IHTMLDocument2) webBrowser1.Document.DomDocument;  VDocument.parentWindow.execScript ("function confirm (str) {return true;}", "JavaScript"); Pop-Up confirmation  vDocument.parentWindow.execScript ("function alert (str) {return true;}", "JavaScript");//Popup prompt}

After the 12.WebBrowser page has been loaded, auto-click (block) of the popup box when you do some automation in the page:

private void Webbrowser1_documentcompleted (object sender, WebBrowserDocumentCompletedEventArgs e) {    // Auto-click Pop-Up confirmation or pop-up hint    IHTMLDocument2 vdocument = (IHTMLDocument2) webBrowser1.Document.DomDocument;    VDocument.parentWindow.execScript ("function confirm (str) {return true;}", "JavaScript"); Pop-Up confirmation    vDocument.parentWindow.execScript ("function alert (str) {return true;}", "JavaScript");/    /popup Prompt// Here's your Code of execution:}

13. Get the IFRAME in the Web page and set the src of the IFRAME:

HTMLDocument docframe = webbrowser1.document.window.frames["MainFrame"]. Document; or HTMLDocument docframe = webbrowser1.document.all.frames["MainFrame"]. Document; docframe.all["MainFrame"]. SetAttribute ("src", "http://www.baidu.com/");

When there is an IFRAME in the page Webbrowser1.url and webbrowser1_documentcompleted in the E.url, the former is the main frame URL, which is the current active box port URL.

14. Let the control focus:

This.webBrowser1.Select (); This.webBrowser1.Focus ();d OC. all["Tpl_password_1"]. Focus ();

15. Open the local webpage file:

WebBrowser1.Navigate (Application.startuppath + @ "\test.html");

16. Get elements and forms:

Gets the element public htmlelement getelement_name (WebBrowser wb,string name) {    HtmlElement e = WB according to the name. Document.all[name];    return e;} Gets the element public htmlelement getelement_id (WebBrowser WB, string ID) based on the ID {    HtmlElement e = wb. document.getElementById (ID);    return e;} Gets the element public htmlelement getelement_index (WebBrowser wb,int index) {    HtmlElement e = WB according to index. Document.all[index];    return e;} Get form table sole name name, return form public htmlelement getelement_form (WebBrowser wb,string form_name) {    htmlelement e = wb. Document.forms[form_name];    return e;}  Sets the value of the element Value property public void Write_value (HtmlElement e,string value) {    E.setattribute ("value", value);}//method that executes the element, such as: click,submit (need form table sole name) such as public void Btn_click (HtmlElement e,string s) {     e.invokemember (s);}

17. Obtaining Cookies:

[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 lpreserv ED);
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; } }}

18. Set up the agent:

1. First build a structure of agent information

<summary>///agent struct///</summary>public struct struct_internet_proxy_info{public    int dwAccessType ;    Public IntPtr PROXY;//IP and port number public    IntPtr proxybypass;}

2. Setting up the specific implementation of the agent

<summary>///setting agent api///</summary>///<returns></returns>
[DllImport ("Wininet.dll", SetLastError = True)]private static extern bool InternetSetOption (IntPtr hinternet, int Dwoption, IntPtr lpbuffer, int lpdwbufferlength);
<summary>///proxy IP and port number///</summary>///<param name= "Strproxy" ></param>private void Refreshiesettings (String strproxy) {const int internet_option_proxy = 38; const int internet_open_type_proxy = 3; Struct_internet_proxy_info Struct_ipi; Filling in structure struct_ipi.dwaccesstype = Internet_open_type_proxy; Struct_ipi.proxy = Marshal.stringtohglobalansi (strproxy); Struct_ipi.proxybypass = Marshal.stringtohglobalansi ("local"); allocating memory IntPtr intptrstruct = Marshal.alloccotaskmem (marshal.sizeof (STRUCT_IPI)); Converting structure to INTPTR marshal.structuretoptr (Struct_ipi, intptrstruct, true); BOOL Ireturn = InternetSetOption (IntPtr.Zero, Internet_option_proxy, Intptrstruct, marshal.sizeof (Struct_IPI));}

3. When you use it, call it directly.

Refreshiesettings ("41.129.53.227:80"); WebBrowser1.Navigate ("http://www.baidu.com");

19. How to execute code after loading a page:

This event is a private void webbrowser1_documentcompleted (object sender) that executes after each load completes the current page. WebBrowserDocumentCompletedEventArgs e) {     //e.url is the currently loaded page,     if (e.url.tostring (). Contains ("http://www.google.com"))     {     //Perform action 1     }     else if (e.url.tostring (). Contains ("http://www.baidu.com"))     {     //Execute action 2     }}

20. How to prohibit opening a Web page in a new window:

private void Webbrowser1_newwindow (object sender, CancelEventArgs e) {    string url = ( System.Windows.Forms.WebBrowser) sender). StatusText;    WebBrowser1.Navigate (URL);    E.cancel = true;}

21. How to set Cookies:

Webbrowser1.document.cookie= "Your Cookie value";

C#webbrowser control using tutorials and tips for collecting

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.