如何突出显示WebBrowser控件C#中的特定单词

我有一个webbrowser控件,我可以得到用户选择的单词。 我将这个单词保存在一个文件中,并且使用它我也保存它的字节偏移量和长度。

让我说我的Web浏览器控件中有一些文本为“Hello Hey Hello”让我们说用户选择了最后一个hello。

现在这个单词和我一起保存,以及其长度等其他信息。

当用户重新加载文件时,我需要提供一个突出显示所选单词的function,并将该单词及其长度和字节偏移量发送给我

有没有办法做到这一点。

如果你还没有,你将需要导入Microsoft.mshtml程序集引用,并添加

using mshtml; if (webBrowser1.Document != null) { IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2; if (document != null) { IHTMLBodyElement bodyElement = document.body as IHTMLBodyElement; if (bodyElement != null) { IHTMLTxtRange trg = bodyElement.createTextRange(); if (trg != null) { const String SearchString = "Privacy"; // This is the search string you're looking for. const int wordStartOffset = 421; // This is the starting position in the HTML where the word you're looking for starts at. int wordEndOffset = SearchString.Length; trg.move("character", wordStartOffset); trg.moveEnd("character", wordEndOffset); trg.select(); } } } } 

这是一个可能也有帮助的片段:

  if (webBrowser1.Document != null) { IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2; if (document != null) { IHTMLSelectionObject currentSelection = document.selection; IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null) { const String search = "Privacy"; if (range.findText(search, search.Length, 2)) { range.select(); } } } } 

我是新手程序员是我最好的样本。 只是花了很多时间。

只需连接你的图书馆

项目 – 添加链接 – 概述 – windows – system32 – mshtml.tlb

 using mshtml; private void button1_Click(object sender, EventArgs e) { webBrowser1.Refresh(); Application.DoEvents(); if (webBrowser1.Document != null) { IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2; if (document != null) { IHTMLSelectionObject currentSelection = document.selection; IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null) { String search = textBox1.Text; if (search == "") { MessageBox.Show("not selected"); } else { line1: if ((range.findText(search)) && (range.htmlText != "span style='background-color: rgb(255, 255, 0);'>" + textBox1.Text + "")) { range.select(); range.pasteHTML("" + textBox1.Text.ToLower() + ""); goto line1; } } } } } }