I try to have the find dialog feature in my webbroser control, it should search several words (forward) and highlight them. I tried the following code from this MSDN question
private bool FindFirst(string text)
{
IHTMLDocument2 doc = (IHTMLDocument2)browserInstance.Document;
IHTMLSelectionObject sel = (IHTMLSelectionObject)doc.selection;
sel.empty(); // get an empty selection, so we start from the beginning
IHTMLTxtRange rng = (IHTMLTxtRange)sel.createRange();
if (rng.findText(text, 1000000000, 0))
{
rng.select();
return true;
}
return false;
}
However this code and the code in the original question search the entire document and use range = body.createTextRange()
to create a range, I would like to search within a specific element (for example just text in a specific div
)
How can I do that?
I solved the problem by adding moveToElementText(..) to the code. It moves the text range so that the start and end positions of the range encompass the text in the given element.
bool FindFirst(HtmlElement elem, string text)
{
if (elem.Document != null)
{
IHTMLDocument2 doc =
elem.Document.DomDocument as IHTMLDocument2;
IHTMLSelectionObject sel = doc.selection as IHTMLSelectionObject;
sel.empty();
IHTMLTxtRange rng = sel.createRange() as IHTMLTxtRange;
// MoveToElement causes the search begins from the element
rng.moveToElementText(elem.DomElement as IHTMLElement);
if (rng.findText(text, 1000000000, 0))
{
rng.select();
rng.scrollIntoView(true);
return true;
}
}
return false;
}
public bool FindNext(HtmlElement elem, string text)
{
if (elem.Document != null)
{
IHTMLDocument2 doc =
elem.Document.DomDocument as IHTMLDocument2;
IHTMLSelectionObject sel = doc.selection as IHTMLSelectionObject;
IHTMLTxtRange rng = sel.createRange() as IHTMLTxtRange;
rng.collapse(false);
if (rng.findText(text, 1000000000, 0))
{
rng.select();
rng.scrollIntoView(true);
return true;
}
}
return false;
}