C # collection of WebBrowser control tutorials and tips,

Source: Internet
Author: User

C # collection of WebBrowser control tutorials and tips,

 

Common attributes and Methods

Navigate (string urlString): browse URL Navigate (System. uri url): the url Navigate (string urlString, string targetFrameName, byte [] postData, string additionalHeaders): the url indicated by urlString, and send the message in postData // (usually we will send the user name and password as postData when logging on to a website) GoBack (): backward GoForward (): Forward Refresh (): refresh Stop (): Stop GoHome (): common property of the WebBrowser control on the browser page: Document: Get the currently viewed Document DocumentTitle: Get the currently viewed webpage title StatusText: get the text Url of the Current Status Bar: Get the UriReadyState of the Url currently being browsed: Get the browsing status common events of the WebBrowser control: DocumentTitleChanged, CanGoBackChanged, CanGoForwardChanged, DocumentTitleChanged, ProgressChanged, the event copy code after the ProgressChangedDocumentCompleted page is loaded

1. Obtain the value of a 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 tag "). getElementsByName ("Control name attribute") [0]. getAttribute ("style"); // obtain an element through a tag

2. Obtain the value of the input control:

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

3. assign a value to the input box:

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

4. drop-down, check, and multiple options:

// Drop-down box: secret. setAttribute ("value", "question1"); // check box rememberme. setAttribute ("Checked", "True"); // multiple choice box cookietime. setAttribute ("checked", "checked ");

5. Operate the element without ID based on the known element with ID:

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

6. Get the style of the Div or other elements:

webBrowser1.Document.GetElementById("addDiv").Style;
7. directly execute the Script Function on the page, with dynamic parameters or without parameters.:
Object[] objArray = new Object[1];objArray[0] = (Object)this.labFlightNumber.Text;webBrowser1.Document.InvokeScript("ticketbook", objArray);webBrowser1.Document.InvokeScript("return false");

8. Automatic clicking and automatic submission:

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

9. automatically assign values. If a script error or loading problem occurs when you click the submit button, the event is usually clicked too quickly. In this case, you need to use the Timer control or Application. doEvents:

This. timer1.Enabled = true; this. timer1.Interval = 1000*2; private void timer1_Tick (object sender, EventArgs e) {this. timer1.Enabled = false; ClickBtn. invokeMember ("Click"); // execute the button operation}
Private void DelayClick () {// The following Code indicates that the click operation is delayed by 1 second and will not be like Thread. sleep (1000) will cause a temporary false death of the program, but the efficiency will be reduced by DateTime time = DateTime. now; while (time. addSeconds (1) <time) {Application. doEvents ();} ClickBtn. invokeMember ("Click"); // execute the button operation}
Supplement: Role of Application. DoEvents () in C #

Summary in Visual Studio: processes all Windows messages in the message queue.
The CPU control is handed over so that the system can process all Windows messages in the queue, such as adding Application in a large computing cycle. doEvents can prevent the interface from stopping the response. Because the message loop of winform is processed by a thread, if one of your operations is time-consuming, message processing must be completed before the operation can continue, and Application. the DoEvents method allows you to call it internally during time-consuming operations to process messages in the message queue. Windows messages are like moving the mouse and clicking the mouse. If time-consuming operations are always performed, the interface is like a deadlock. It is worth noting that using Application. DoEvents also reduces program performance.

(Application. DoEvents is used in many time-consuming operations)

10. Script blocking error:

Set the WebBrowser control ScriptErrorsSuppressed to True.

11. Automatically click the pop-up prompt box: to use IHTMLDocument2, you must add a reference to the Microsoft HTML Object Library:

(If there is no Microsoft HTML Object Library, add the COM component first, and introduce Microsoft. mshtml. dll to the browser file. The file address is C: \ WINDOWS \ system32 \ mshtml. dll)

Private void webbrowserinclunavigated (object sender, WebBrowserNavigatedEventArgs e) {// click the pop-up confirmation or the prompt IHTMLDocument2 vDocument = (IHTMLDocument2) webBrowser1.Document appears. domDocument; vDocument.parentWindow.exe cScript ("function confirm (str) {return true;}", "javascript"); // the pop-up confirmation vDocument.parentWindow.exe cScript ("function alert (str) {return true;} "," javaScript "); // a prompt is displayed}

12. After the WebBrowser page is loaded, click (Block) in the pop-up box when performing some automated operations on the page ):

Private void webbrowserincludocumentcompleted (object sender, WebBrowserDocumentCompletedEventArgs e) {// click the pop-up confirmation or the prompt IHTMLDocument2 vDocument = (IHTMLDocument2) webBrowser1.Document appears. domDocument; vDocument.parentWindow.exe cScript ("function confirm (str) {return true;}", "javascript"); // the pop-up confirmation vDocument.parentWindow.exe cScript ("function alert (str) {return true;} "," javaScript "); // a prompt is displayed. // your Execution Code is shown below}

13. Get the Iframe In the webpage and set the src of 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 an Iframe exists in a webpage, webBrowser1.Url is different from e. Url in webBrowser1_DocumentCompleted. The former is the Url of the main frame, and the latter is the Url of the current active frame port.

14. Focus controls on:

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

15. Open a local webpage file:

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

16. Obtain elements and forms:

// Obtain the public HtmlElement GetElement_Name (WebBrowser wb, string Name) {HtmlElement e = wb according to Name. document. all [Name]; return e;} // obtain the public HtmlElement GetElement_Id (WebBrowser wb, string Id) {HtmlElement e = wb. document. getElementById (id); return e;} // obtain the public HtmlElement GetElement_Index (WebBrowser wb, int Index) {HtmlElement e = wb. document. all [index]; return e;} // get form name, return form public HtmlElement GetElement_Form (WebBrowser wb, string form_name) {HtmlElement e = wb. document. forms [form_name]; return e;} // set the value of the element value attribute public void Write_value (HtmlElement e, string value) {e. setAttribute ("value", value);} // method of executing elements, such as: click, submit (Form name required) and other public void Btn_click (HtmlElement e, string s) {e. invokeMember (s );}

17. Obtain Cookie:

[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;              }          }      }

18. Set Proxy:

1. First, create a proxy information structure.

/// <Summary> /// proxy struct /// </summary> public struct Struct_INTERNET_PROXY_INFO {public int dwAccessType; public IntPtr proxy; // IP address and port number public IntPtr proxyBypass ;};

2. Set specific proxy implementation

/// <Summary> /// set the proxy 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 address 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 =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. You can directly call it when using it.

RefreshIESettings("41.129.53.227:80");webBrowser1.Navigate("http://www.baidu.com");

19. How to execute code after loading a page:

// This event is the private void webbrowserincludocumentcompleted (object sender, WebBrowserDocumentCompletedEventArgs e) that will be executed after the current page is loaded every time. {// e. the Url is the currently loaded page, if (e. url. toString (). contains ("http://sufeinet.com") {// perform operation 1} else if (e. url. toString (). contains ("http://baidu.com") {// perform operation 2 }}

20. How to disable opening a webpage 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 ";

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.