我有一个webbrowser控件,我可以通过用户获取所选单词。 我将这个单词保存在一个文件中,并且使用它我也保存了它的字节偏移量和长度。
Lets说我的Web浏览器控件中有一些文本为“Hello Hey Hello”,假设用户选择了最后一个问候语。
现在,这个单词与我一起保存,以及其长度等其他信息。
当用户重新加载文件并向我发送该字及其长度和字节偏移时,我需要提供一个突出显示所选字的功能
有没有办法做到这一点。
答案 0 :(得分:6)
如果您还没有,则需要导入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();
}
}
}
}
答案 1 :(得分:1)
我是新手程序员是我最好的样本。只是花了很多时间。
只需连接您的图书馆
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;
}
}
}
}
}
}