2015-04-28 36 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; 
    }