WebBrowser page and WinForm interaction skills)

Source: Internet
Author: User
The following code assumes that you have created a Windows Form with the WebBrowser name "webBrowser ".

Study Case 1: Use WinForm Event Handler to respond to webpage events

Now there is a Windows Application with only one WebBrowser on its interface, displaying a local HTML file as the interface. The problem now is that all logic can be stored in HTML files, but the "close" button has encountered difficulties-generally, there is no way to directly control the browser on Web pages, let alone end the WinForm program.

However, in. Net 2.0, "Responding to web page events by Windows Form" has become a reality.

In. Net 2.0, the entire HTML document and its various HTML elements correspond to. Net objects such as HtmlDocument and HtmlElement. Therefore, you only need to find the HtmlElement object corresponding to the "close" button and add Event Handler for its click Event.

Assume that the HTML source code is as follows:

 
<Html> <body> <input type = "button" id = "btnClose" value = "close"/> </body> 
<Html> <br/> <body> <br/> <input type = "button" id = "btnClose" value = "close"/> <br/> </body> <br/> </ptml>

The code for finding this button and adding Event Handler to it is as follows:

HtmlDocument htmlDoc = webBrowser.Document;HtmlElement btnElement = htmlDoc.All["btnClose"];if (btnElement != null){btnElement.click += new HtmlElementEventHandler(HtmlBtnClose_Click);}

HtmlBtnClose_Click is the Event Handler when the Web button is pressed.

Is it easy? A little more advanced-we all know that an HTML element may have many kinds of events, while the HtmlElement class only provides the most common and common events. So how to respond to other events? This is also very simple. You only need to call the AttachEventHandler of HtmlElement:

BtnElement. AttachEventHandler ("onclick", new EventHandler (HtmlBtnClose_Click); // This sentence is equivalent to the above btnElement. click + = new HtmlElementEventHandler (HtmlBtnClose_Click );

For other events, replace "onclick" with the name of the event. For example:

formElement.AttachEventHandler("onsubmit", new EventHandler(HtmlForm_Submit));

Study Case 2: Automatic Filling and submission of forms

It is not difficult to make our WebBrowser have the function of automatically filling out tables or even submitting tables.

Assume there is a simple logon page. Enter the user name and password and click "Log on" to log on. It is known that the user Name input box id (or Name, the same below) is username, the password input box id is password, the login button id is submitbutton, then we only need to use the following code in the DocumentCompleted event of webBrowser:

HtmlElement btnSubmit = webBrowser.Document.All["submitbutton"];HtmlElement tbUserid = webBrowser.Document.All["username"];HtmlElement tbPasswd = webBrowser.Document.All["password"];if (tbUserid == null || tbPasswd == null || btnSubmit == null)return;tbUserid.SetAttribute("value", "smalldust");tbPasswd.SetAttribute("value", "12345678");btnSubmit.InvokeMember("click");

Here we use SetAttribute to set the "value" attribute of the text box, And InvokeMember to call the "click" method of the button. Because different Html elements have different attributes and methods. net 2.0 provides a unified HtmlElement to summarize various Html elements, while providing these two methods to call the features unique to the element. For details about the attributes and methods of various Html elements, refer to the DHTML Reference of MSDN.
Http://msdn.microsoft.com/workshop/author/dhtml/reference/dhtml_reference_entry.asp

※For form submission, another method is to obtain the form element instead of the button and use the submit method of the form element:

HtmlElement formLogin = webBrowser.Document.Forms["loginForm"];//……formLogin.InvokeMember("submit");

This method is not recommended in this article because many of the current web pages add onclick events on the submit button to perform the most basic verification on the submitted content. If you directly use the form submit method, the verification code will not be executed and may cause errors.

Study Case 3: search for and select text

This time we hope to implement the same search function as IE to search for text on the Web page.

The findText method of the TextRange object. However,. Net does not have this object. This is because. Net 2.0 provides classes such as HtmlDocument, HtmlWindow, and HtmlElement, which are incomplete encapsulation of the COM component of the original mshtml and only provide partial mshtml functions. So in many cases, we still need to use mshtml to implement the functions we need. Fortunately, these. Net classes provide the DomDocument attribute, which makes it easy to convert. Net objects to COM objects. The following code demonstrates how to find the web page text.
(You need to add a reference to mshtml and add using mshtml ;)

Public partial class SearchDemo: Form {// create a search TextRange (IHTMLTxtRange Interface) private IHTMLTxtRange searchRange = null; public SearchDemo () {InitializeComponent ();} private void btnSearch_Click (object sender, EventArgs e) {// DomDocument attribute of the Document, which is the COM object inside the object. IHTMLDocument2 document = (IHTMLDocument2) webBrowser. document. domDocument; string keyword = txtKeyword. text. trim (); if (keyword = "") return; // The search logic of IE is: if a selection area exists, search from the beginning of the current selection + 1 character; if not, search for the page from the beginning. // This logic is a bit inappropriate. We don't need to worry about it here. It's just the same as IE. If (document. selection. type. ToLower ()! = "None") {searchRange = (IHTMLTxtRange) document. selection. createRange (); searchRange. collapse (true); searchRange. moveStart ("character", 1);} else {IHTMLBodyElement body = (IHTMLBodyElement) document. body; searchRange = (IHTMLTxtRange) body. createTextRange () ;}// if the keyword is found, select (highlighted). Otherwise, the message is displayed. If (searchRange. findText (keyword, 1, 0) {searchRange. select ();} else {MessageBox. Show ("the end of the document has been found. ");}}}

So far, simple search is done. As for the replacement function, I have read the next example. I believe you can easily touch the analogy.

Study Case 4: highlighted

In the previous example, we learned to search for text, which is to check whether the webpage is read-only or not. So what if we want to highlight all the search results? We will soon think of changing the color and background of all matched texts.

The first thing that comes to mind is to directly modify the HTML text ...... However, unlike the highlighted display of SourceCode, we only need to highlight the text part of the page. HTML tags, script code, and so on should never be modified. Therefore, we cannot read the Source Code of the entire page and then replace it, which may damage the structure of the HTML file. We can only separate the text from other content (tags, scripts ......) .

There are many specific methods. The following two simple methods are provided.

Method 1: Use TextRange (IHTMLTxtRange)

With the foundation of the previous Case, I believe you will immediately think of using TextRange. In addition to the search method, TextRange also provides a pasteHTML method to replace the content in the current TextRange with the specified HTML text. The code snippet is as follows:

Public partial class HilightDemo: Form {// defines the label of the highlighted effect. String tagBefore = "<span style = 'background-color: yellow; color: black'>"; string tagAfter = "</span> ";//...... Private void btnHilight_Click (object sender, EventArgs e) {HtmlDocument htmlDoc = webBrowser. document; string keyword = txtKeyword. text. trim (); if (keyword = "") return; object oTextRange = htmlDoc. body. invokeMember ("createTextRange"); mshtml. IHTMLTxtRange txtrange = oTextRange as mshtml. IHTMLTxtRange; while (txtrange. findText (keyword, 1, 4) {try {txtrange. pasteHTML (tagBefore + keyword + tagAfter);} catch {} txtrange. collapse (false );}}}

※The IHTMLTxtRange acquisition method in this code is slightly different from the above example. In fact, the so-called things are essentially the same as Rome.

Method 2: Use DOM (Document Object Model)

Parse the HTML document to the DOM, traverse each node, search for keywords and replace them accordingly.

Public partial class HilightDemo: Form {//...... Private void btnHilight_Click (object sender, EventArgs e) {HTMLDocument document = (HTMLDocument) webBrowser. document. domDocument; IHTMLDOMNode bodyNode = (IHTMLDOMNode) webBrowser. document. body. domElement; string keyword = txtKeyword. text. trim (); if (keyword = "") return; HilightText (document, bodyNode, keyword);} private void HilightText (HTMLDocument document, IHTMLDOMNode node, string keyword) {// node Type = 3: if (node. nodeType = 3) {string nodeText = node. nodeValue. toString (); // if the keyword if (nodeText. contains (keyword) {IHTMLDOMNode parentNode = node. parentNode; // use the keyword as the separator to separate the text and add it to the parent node of the original text node one by one. string [] result = nodeText. split (new string [] {keyword}, StringSplitOptions. none); for (int I = 0; I <result. length-1; I ++) {if (result [I]! = "") {IHTMLDOMNode txtNode = document. createTextNode (result [I]); parentNode. insertBefore (txtNode, node);} IHTMLDOMNode orgNode = document. createTextNode (keyword); IHTMLDOMNode hilightedNode = (IHTMLDOMNode) document. createElement ("SPAN"); IHTMLStyle style = (IHTMLElement) hilightedNode ). style; style. color = "black"; style. backgroundColor = "yellow"; hilightedNode. appendChild (orgNode); parentNode. insertBef Ore (hilightedNode, node);} if (result [result. Length-1]! = "") {IHTMLDOMNode postNode = document. createTextNode (result [result. length-1]); parentNode. insertBefore (postNode, node);} parentNode. removeChild (node);} // End of nodeText. contains (keyword)} else {// if it is not a text node, Recursively search its subnode IHTMLDOMChildrenCollection childNodes = node. childNodes as IHTMLDOMChildrenCollection; foreach (IHTMLDOMNode n in childNodes) {HilightText (document, n, keyword );}}}}

The above two sections of code are simplified to be clear and easy to understand, and many of them are not perfect. For example, it does not take into account how to restore from the highlighted status, and there is no case matching. Of course, it will not be too difficult to believe this after you have mastered the principles.

The two methods have their own advantages and disadvantages:
TextRange is a lightweight and rapid method, and a special feature is that you can pick out the keywords of cross-Tag. For example, there is such HTML:

<b>Hel</b>lo World!
<B> El </B> lo World!

No matter what purpose the author makes the three letters of El bold, the "Hello World!" message is displayed on the page !". When we want to highlight the keyword "Hello" on the page, if we use DOM analysis, we will get the <B> node and text node "lo World!" with "El !" Two nodes cannot be picked out. TextRange can correctly identify and set it to highlight. Therefore, TextRange is an object only related to text and irrelevant to the HTML syntax structure.

However, TextRange also has its fatal drawbacks. It is easy to highlight and reverse. In other words, TextRange cannot be used when highlighting is removed, but other methods are required.

The DOM method is the opposite. Because of the tree structure of DOM, although it cannot (or is difficult) span Tag search keywords, It is not cumbersome to remove the highlighted display.

Study Case 5: interoperability with scripts

In Case 1, we have seen that the HTML element event on the Web page can be responded by Windows Form, which can be viewed as a Web page calling WinForm to some extent, in addition to the HTML elements on the Web page, can WinForm call various scripts on the Web page?

First, call the functions defined in the webpage script. Suppose the HTML contains the following Javascript:

function DoAdd(a, b) {return a + b;}

To call it in WinForm, you only need the following code:

object oSum = webBrowser.Document.InvokeScript("DoAdd", new object[] { 1, 2 });int sum = Convert.ToInt32(oSum);

What should we do if we want to execute a script that is not available on a Web page? This time, the. Net class is not provided, and it seems that it depends on COM. IHTMLWindow2 can execute arbitrary strings as script code.

String scriptline01 = @ "function ShowPageInfo () {"; string scriptline02 = @ "var numLinks = document. links. length; "; string scriptline03 = @" var numForms = document. forms. length; "; string scriptline04 = @" var numImages = document. images. length; "; string scriptline05 = @" var numScripts = document. scripts. length; "; string scriptline06 = @" alert ('webpage statistics: \ r \ n connections: '+ numLinks + "; string scriptline07 = @ "'\ r \ n number of forms:' + numForms +"; string scriptline08 = @ "'\ r \ n number of images:' + numImages + "; string scriptline09 = @ "'\ r \ n script count:' + numScripts);}"; string scriptline10 = @ "ShowPageInfo ();"; string strScript = scriptline01 + scriptline02 + scriptline03 + scriptline04 + response + scriptline06 + scriptline07 + scriptline08 + scriptline09 + scriptline10; IHTMLWindow2 win = javascscript (strScript, "Javascript ");

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.