2015-04-28 38 views
0

我尝试在我的webbroser控件中查找对话框功能,它应该搜索几个单词(向前)并突出显示它们。 我试图从this MSDN questionWeb浏览器查找html元素中文本的对话框

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; 
    } 

下面的代码但是这个代码,并在原来问题的代码搜索整个文档,并使用range = body.createTextRange()创建范围,我想一个特定的元素中进行搜索(例如只中的文字div

我该怎么做?

回答

0

我通过将moveToElementText(..)添加到代码中解决了问题。它移动文本范围,以便范围的开始位置和结束位置包含给定元素中的文本。

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; 
    }