.NET 2.0 instance learning: WebBrowser page and WinForm interaction skills

xiaoxiao2021-03-17  201

Nearly see the introductory articles in the blog garden, it is more popular, and it is more lazy recently. It doesn't have a good experience. I don't write a departure article.

Say that there is a WebBrowser class, and finally don't have to manually encapsulate SHDOCVW's AxWebBrowser this ActiveX control. If this class is just as a browser as an exact same, it is too boring (it is better to use IE directly). So, whether we want to be a "custom version IE", you still want to use HTML to do user interface (refer to WinApp instead of webapp. Many stand-alone software, including Windows Help Support Center, all HTML do), you can't do Windows FORM and interaction of web pages contained in WebBrowser. This article will introduce the interaction between WINFORM and WebBBrowser in the web page included in this article.

The following code assumes that you have established a Windows Form, which has a WebBrowser name "WebBrowser".

Study Case 1: Responding to the event of the web page with WinForm's Event Handler

Now there is such a Windows Application, there is only one webbrowser on its interface, displaying a local HTML file as an interface. The current problem is that all logic can be placed in an HTML file, and only the "Close" button has encountered difficulties - usually, the web page is not a way to directly control the browser, not to mention the WinForm program.

However, in .NET 2.0, "Events in response to the web page" by Windows Form "have become reality.

In .NET 2.0, the entire HTML document and each HTML element therebetween, all HTMLDocument, HTMLELEMENT .NET objects. So just find the HTMLELEMENT object corresponding to this "Close" button, add Event Handler for its Click event. Suppose the HTML source code is as follows:

Then find that the button is added and the code for Event Handler is as follows:

HTMLDocument HTMLDOC =

Webbrowser.document; htmlelement btnelement = htmldoc.all ["btnclose"

]; if (btnelement! = null

) {Btnelement.click = new

HTMLELEMENTEVENTHANDLER (htmlbtnclose_click);

Where htmlbtnclose_click is an Event Handler that presses the web button.

Very simple? So a little more advanced - we all know that an HTML element may have a lot of events, while HTMLELEMENT is only given to several common, several common. So how do you respond to other events? This is also very simple, just call HTMLELEMENTHANDLER:

Btnelement.attacheventhandler ("onclick", New

EventHandler (HTMLBTNCLOSE_Click); // This sentence is equivalent to btrnelement.click = new htmlelementeventHandler (HTMLBTNCLOSE_CLICK); for other events, "OnClick" is replaced with the name of the event. E.g:

ForMelement.attacheventhandler ("OnSubmit", New EventHandler (HTMLFORM_SUBMIT);

STUDY CASE 2: Form (FORM) Automatic Filling and Submission To make our webbrowser have automatic filler, and even automatic functions are not difficult.

Suppose there is a simpler login page, enter the username password, and click the "Login" button to log in. Known username input box ID (or Name, below) is username, password input box ID is Password, "Login" ID is Submitbutton, then we only need to use the following code in WebBrowser's DocumentCompleted event can:

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.SETATITRIBUTE ("Value", "Smalldust"

); tbpasswd.setttribute ("Value", "12345678"

Btnsubmit.invokeMember ("Click");

Here we use setAttribute to set the "value" property of the text box, use InvokeMember to call the "Click" method of the button. Because different HTML elements, their properties and methods are not the same, so .NET 2.0 provides unified HTMLEMENT to summarize the various HTML elements, providing these two methods to invoke elementality features. For the properties and methods of various HTML elements, you can check the MSDN's DHTML Reference.

※ Regarding the submission of the form, there is indeed another way to get the FORM element instead of button, and use the Submit method for FORM element:

HTMLELEMENT FORMLOGIN = WebBrowser.document.Forms ["Loginform"

]; // ......

Formlogin.invokemember ("Submit");

This method does not recommend this method because the current webpage is now added to the Submit button to add the onclick event to the submitted content. If you use the Submit method directly, these verification code is not executed, and it is possible to cause errors. Study Case 3: Find and select Text This time we want to implement one of the same lookup functions as IE to find text on the web page.

Text Finding To use the FindText method of the TextRange object. However, there is no object in .NET. This is because, .NET 2.0 is provided by HTMLDocument, HTMLWindow, Htmlelelement, etc., only for incomplete packages of the original MSHTML COM components, only part of the MSHTML. So many times, we still have to achieve the functions we need with MSHTML. Fortunately, these .NET classes provide DomDocument properties so that we can easily convert the .NET object to a COM object. The following code demonstrates how to find the text of the web page. (Recommended by MSHTML, add USING MSHTML;) Public Partial Class

SearchDemo: form {// Building a lookup TextRange (IHTMLTXTRANGE interface)

Private IHTMLTXTRANGE SEARCHRANGE = NULL

PUBLIC

SearchDemo () {InitializationComponent (); private void btnsearch_click (Object

Sender, Eventargs E) {// Document DomDocument property is the COM object inside the object.

Htmldocument2 document =

(Htmldocument2) webbrowser.document.domdocument; String Keyword =

TXTKEYWORD.TEXT.TRIM (); if (keyword == ""

) Return

; //

The search logic of IE is that if there is a constituency, start looking for from the beginning 1 character of the current selection; if not, you will start looking for it. // This logic is actually a bit unclear, we don't use the tube here, and you can consistent with IE.

IF (Document.Serection.Type.tolower ()! = "none"

) {SearchRange =

(IHTMLTXTRANGE) Document.Selection.createRANGE (); SearchRange.collapse

SearchRange.Movestart ("Character", 1

Else

{IhtmlBodyElement Body

=

(HtmlbodyElement) Document.body; searchRange =

(HtmltxtRange) Body.createTextRange ();} // If you are found, select (highlight) the keyword; otherwise pop up the message.

IF (SearchRange.FindText (Keyword, 1, 0

)) {SearchRange.select ();} else

{MessageBox.show ("has been searched for the end of the document."

}}}

So far, simple look is getting it. As for the replacement, I looked at the next example, I believe you can touch the class bypass. Study Case 4: Garently displayed in an example we learned to find text - he followed, for the web page or read only. So, if you want to highlight all the search results? We will soon think of all matching text colors, backgrounds can be changed.

The first thing I think is that I can modify the HTML text ... However, the highlights of Sourcecode are different, we need and only need the text section in the highlight. HTML tags, script code, etc. are absolutely should not be changed. So we can't read the Source Code of the entire page. There are a lot of specific methods, and two relatively simple methods are provided below.

Method 1: With TextRange (IHTMLTXTRANGE) has the foundation of the last CASE, I believe that everyone will immediately think of using TextRange. That's right, in addition to providing a lookup method, TextRange provides a Pastehtml method to replace the contents of the current TextRange in the specified HTML text. The code segment is as follows:

Public Partial CLASS

HilightDemo: form {// Defines the tab that highlights the effect.

String tagbefore = ""

String tagafter = ""

; // ......

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.ihtmltxtXtrange txtrange = OTEXTRANGE AS

Mshtml.ihtmltxtXtrange; while (TXTRANGE.FINDTEXT (Keyword, 1, 4

)) {TRY

{TXTRANGE.PASTEHTML (Tagbefore Keyword

Tagafter; catch

{} TXTRANGE.COLLLAPSE (False)

}}}

※ This code has been obtained in the way IhtmltXTrange and the above example is slightly different. In fact, the so-called rosewarted road is the same, the essence is the same. Method 2: Use the DOM (Document Object Model) to resolve the HTML document to the DOM, then traverse each node, search the keyword in it and perform the corresponding replacement process. Public Partial CLASS

Hilightdemo: form {// ......

Private void btnhilight_click (Object

Sender, Eventargs E) {htmldocument document =

(Htmldocument) webbrowser.document.domdocument; htmldomnode body bodynode =

(Htmldomnode) webbrowser.document.body.domElement; String Keyword =

TXTKEYWORD.TEXT.TRIM (); if (keyword == ""

) Return

HilightText (Document, Bodynode, Keyword); Private Void HilightText (HTMLDOCUMNODE Node, String

Keyword) {// nodetype = 3: Text node

IF (Node.NodeType == 3

) {String NodeText =

Node.NodeValue.toString (); // If you find a keyword

IF

(nodetext.contains (keyword)) {itmldomnode parentNode =

Node.parentNode; // Use the keyword as a separator, separated the text, and add the parent of the original Text node one by one.

String [] result = nodetext.split (new string

[] {Keyword}, ​​stringsplitoptions.none; for (int i = 0; i

) {If (result [i]! = "

) {Htmldomnode txtNode =

document.createTextNode (result [i]); parentNode.insertBefore (txtNode, node);} IHTMLDOMNode orgNode =

Document.createTextNode (Keyword); htmldomnode hilightedNode = (htmldomnode) Document.createElement ("span"); htmlstyle style =

((Ihtmlelement) hilightedNode) .style; style.color = "black"

Style.BackgroundColor = "Yellow"

HilightedNode.Appendchild (OrgNode); ParentNode.Insertbefore (HilightedNode, Node);}} (Result [Result.length - 1]! = "

) {Itmldomnode postnode = document.createtextNode (Result] - 1

]); Parentnode.insertbefore (postnode, node);} ParentNode.RemoveChild (Node);} // end of nodetext.contains (keyword)

Else

{// If it is not a Text node, recursively search for its child nodes

Htmldomchildrencollection childnodes = node.childNodes as

IHTMLDOMCHILDRENCOLLECTION; Foreach (IHTMLDomnode N in

ChildNodes) {HilightText (Document, N, Keyword);}}}}

The above two codes are clear and easy to understand and streamlined can not be simple, there are many places very difficult. For example, don't take into account how to recover from highlighting status; there is no case match matching, etc. Of course, I believe that these will not be too difficult after mastering the principle. These two methods have advantages and disadvantages: using TextRange quickly, and there is a specialty, it is to pick the keywords across the tab (tag). For example, there is such an HTML:

hell lo world!

No matter what the author has made HEL three letters into bold, in short, it shows a "Hello World!" On the page. When we want to "Hello" in the highlight, if you use DOM analysis, you will get two nodes with "Hel" nodes and text nodes "Lo World!", So you can't To pick out. TextRange can correctly identify and set it to highlight it. Therefore, TextRange can also be said to be related to text, and an object that is not related to the HTML syntax structure. However, TextRange also has its fatal disadvantages, it is easy to brighten, and it is difficult to reverse. In other words, it is necessary to use TextRange when removing highlighting, and other methods need to be used. The DOM method is just the contrary, due to the tree structure characteristics of the DOM, although not (or difficult) spanning the TAG search keyword, it is not cumbersome to remove highlights. Study Case 5: Interoperability with scripts in Case 1, we have seen the HTML element of the web page, can be responded by the Windows Form, can be seen to a web page call winform; then In turn, WinForm can call the various Script in the web page in addition to the HTML element of the web page, in addition to the HTML element of the web page? The first is to call the WEB page's script already defined a function. Suppose HTML is as follows JavaScript: Function

Doadd (A, B) {RETURN A

B;

So, we have to call it in WinForm, just ask the following code:

Object Osum = Webbrowser.document.invokeScript ("Doadd", New Object [] {1, 2

}); int sum = convert.Toint32 (OSUM);

Secondly, if we want to perform the original script in a web page, what should I do? This time .NET's class is not available, it seems to rely on COM. IHTMLWindow2 can perform any string as a 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 (statistics: / r / n link number: ' Numlinks "

String scripTline07 = @ "'/ r / n table:' NumForms "

String scripTline08 = @ "'/ r / n number number:' numimages "; string scriptline09 = @ "'/ r / n script number:' numscripts);}"

String scripTline10 = @ "showpageInfo ();"

; string strscript = scriptline01 scriptline02 scripTline03 scripTline04 scripTline05

Scriptle06

ScripTline07 scripTline08 scriptline09

Scriptle10; htmlwindow2 win =

(Htmlwindow2) WebBrowser.Document.window.Domwindow; Win.execScript (STRScript, "JavaScript");

Http://smalldust.cnblogs.com/archive/2006/03/08/345561.html

转载请注明原文地址:https://www.9cbs.com/read-129715.html

New Post(0)