【问题标题】:How to Highlight a specific word in WebBrowser control C#如何在 WebBrowser 控件 C# 中突出显示特定单词
【发布时间】:2010-11-27 14:41:53
【问题描述】:
我有一个网络浏览器控件,我可以获取用户选择的单词。
我将这个词保存在一个文件中,并用它保存它的字节偏移量和长度。
假设我的 Web 浏览器控件中有一些文本,例如“Hello Hey Hello”,假设用户选择了最后一个 hello。
现在这个词和它的长度等其他信息一起保存在我身边。
当用户重新加载文件并将该单词连同它的长度和字节偏移发送给我时,我需要提供一个功能来突出显示选定的单词
有什么办法吗?
【问题讨论】:
标签:
c#
winforms
webbrowser-control
【解决方案1】:
如果您还没有导入 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();
}
}
}
}
这里有一个可能也有用的 sn-p:
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();
}
}
}
}
【解决方案2】:
我是一个新手程序员是我最好的示例。只是花很多时间。
只需连接您的图书馆
项目-添加链接-概览-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 + "</span>"))
{
range.select();
range.pasteHTML("<span style='background-color: rgb(255, 255, 0);'>" + textBox1.Text.ToLower() + "</span>");
goto line1;
}
}
}
}
}
}