C# .Net 2.0实例学习:WebBrowser页面与WinForm交互技巧,二

上一个例子中我们学会了查找文本——究跟到底,对Web页面还是只读不写。那么,如果说要把所有的搜索结果高亮显示呢?我们很快会想到把所有匹配的文字颜色、背景改一下就可以了。

首先想到的可能是直接修改HTML文本吧……但是,与SourceCode的高亮显示不同,我们需要并且只需要高亮页面中的文本部分。HTML标签、脚本代码等等是绝对不应该去改动的。因此我们不能把整个页面的Source Code读进来然后replace,那样有破坏HTML文件结构的可能;我们只能在能够分离出文本与其他内容(标签,脚本……)的前提下进行。

具体方法有很多,下面提供两个比较简单的方法。

方法一:使用TextRange(IHTMLTxtRange)

有了上一个Case的基础,相信大家立刻会想到使用TextRange。没错,TextRange除了提供查找方法之外,还提供了一个pasteHTML方法,以指定的HTML文本替换当前TextRange中的内容。代码片断如下:

public partial class HilightDemo : Form

{

// 定义高亮显示效果的标签。

string tagBefore ="<span >";

string tagAfter ="</span>";

// ……

privatevoid 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);

}

}

}

※这段代码里获取IHTMLTxtRange的方式和上面的例子稍稍不同,其实所谓条条大路通罗马,本质是一样的。

方法二:使用DOM(文档对象模型)

将HTML文档解析为DOM,然后遍历每个节点,在其中搜索关键字并进行相应替换处理即可。

public partial class HilightDemo : Form

{

//……

privatevoid 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);

}

privatevoid HilightText(HTMLDocument document, IHTMLDOMNode node, string keyword)

{

// nodeType = 3:text节点

if (node.nodeType ==3)

{

string nodeText = node.nodeValue.ToString();

// 如果找到了关键字

if (nodeText.Contains(keyword))

{

IHTMLDOMNode parentNode = node.parentNode;

// 将关键字作为分隔符,将文本分离,并逐个添加到原text节点的父节点

string[] result = nodeText.Split(newstring[] { 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.insertBefore(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

{

// 如果不是text节点,则递归搜索其子节点

IHTMLDOMChildrenCollection childNodes = node.childNodes as IHTMLDOMChildrenCollection;

foreach (IHTMLDOMNode n in childNodes)

{

HilightText(document, n, keyword);

}

}

}

}

上面的两段代码都是为了清晰易懂而精简得不能再简的,有很多地方很不完善。比如,没考虑到如何从高亮显示状态复原;也没有大小写匹配等等。当然,掌握了原理之后相信这些都不会太难。

这两种方法各有优缺点:

使用TextRange较轻量迅速,而且有一个特长,就是可以把跨标签(Tag)的关键字挑出来。例如,有这么一段HTML:

<b>Hel</b>lo World!

先不管作者出于什么目的让Hel三个字母成为粗体,总之显示在页面上的是一句“Hello World!”。在我们希望高亮页面中的“Hello”这个关键字时,如果用DOM分析的话,会得出含有“Hel”的<b>节点和文本节点“lo World!”两个节点,因此无法将其挑出来。而TextRange则能正确识别,将其设置为高亮。因此也可以说TextRange是只和文本有关,和HTML语法结构无关的对象。

但是,TextRange也有其致命缺点,加亮容易,反向的话就很难。换句话说,去除高亮显示的时候不能再用TextRange,而需要采用其他方法。

而DOM方法则正好相反, 由于DOM的树状结构特性,虽然不能(或者很难)跨越Tag搜索关键字,但是去除高亮显示并不繁琐。

Study Case 5:与脚本的互操作

在Case 1当中,我们已经看到,Web页面的HTML元素的事件,可以由Windows Form端来响应,可以在某种程度上看作是Web页面调用WinForm;那么反过来,WinForm除了可以直接访问Web页面的HTML元素之外,能否调用Web页面里的各种Script呢?

首先是调用Web页面的脚本中已经定义好的函数。假设HTML中有如下Javascript:

function DoAdd(a, b) {

return a + b;

}

那么,我们要在WinForm调用它,只需如下代码即可:

object oSum = webBrowser.Document.InvokeScript("DoAdd", newobject[] { 1, 2 });

int sum = Convert.ToInt32(oSum);

其次,如果我们想执行一段Web页面中原本没有的脚本,该怎么做呢?这次.Net的类没有提供,看来还要依靠COM了。IHTMLWindow2可以将任意的字符串作为脚本代码来执行。

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('网页的统计结果:\r\n链接数:' + numLinks + ";

string scriptline07 =@" '\r\n表单数:' + numForms + ";

string scriptline08 =@" '\r\n图像数:' + numImages + ";

string scriptline09 =@" '\r\n脚本数:' + numScripts);}";

string scriptline10 =@"ShowPageInfo();";

string strScript = scriptline01 + scriptline02 + scriptline03 + scriptline04 + scriptline05 +

scriptline06 + scriptline07 + scriptline08 + scriptline09 + scriptline10;

IHTMLWindow2 win = (IHTMLWindow2)webBrowser.Document.Window.DomWindow;

win.execScript(strScript, "Javascript");

http://www.xmlasp.net/n1670c13.aspx