2010-10-12 24 views
3

下面是問題: 我想讓我的程序的用戶搜索給定關鍵字(標準的Ctrl + F)的web瀏覽器控件。我在文檔中查找關鍵字沒有問題,並使用span和replace()函數突出顯示所有實例。 I am無法獲得我想要工作的「find next」功能。當用戶點擊Find時,我希望文檔滾動到下一個實例。如果我能得到一個邊界框,我可以使用導航功能。我用下面的代碼如何以編程方式在webBrowser控件中選擇文本? c#

   //Select the found text 
       this.richTextBox.Select(matches[currentMatch], text.Length); 
       //Scroll to the found text 
       this.richTextBox.ScrollToCaret(); 
       //Focus so the highlighting shows up 
       this.richTextBox.Focus(); 

任何人都可以提供一種方法來得到這個在web瀏覽器工作在豐富的文本框此相同的功能的工作?

回答

1

我在具有嵌入式Web瀏覽器控件的WinForms應用程序中實現了搜索功能。它有一個單獨的文本框用於輸入搜索字符串和「查找」按鈕。如果自上次搜索後搜索字符串發生了變化,按鈕點擊意味着定期查找,如果不是,則意味着「再次查找」。這裏是按鈕處理程序:

private IHTMLTxtRange m_lastRange; 
private AxWebBrowser m_browser; 

private void OnSearch(object sender, EventArgs e) { 

    if (Body != null) { 

     IHTMLTxtRange range = Body.createTextRange(); 

     if (! m_fTextIsNew) { 

      m_lastRange.moveStart("word", 1); 
      m_lastRange.setEndPoint("EndToEnd", range); 
      range = m_lastRange; 
     } 

     if (range.findText(m_txtSearch.Text, 0, 0)) { 

      try { 
       range.select(); 

       m_lastRange = range; 

       m_fTextIsNew = false; 
      } catch (COMException) { 

       // don't know what to do 
      } 
     } 
    } 
} 

private DispHTMLDocument Document { 
    get { 
     try { 
      if (m_browser.Document != null) { 
       return (DispHTMLDocument) m_browser.Document; 
      } 
     } catch (InvalidCastException) { 

      // nothing to do 
     } 

     return null; 
    } 
} 

private DispHTMLBody Body { 
    get { 
     if ((Document != null) && (Document.body != null)) { 
      return (DispHTMLBody) Document.body; 
     } else { 
      return null; 
     } 
    } 
} 

m_fTextIsNew在搜索框的TextChanged處理程序中設置爲true。

希望這會有所幫助。

編輯:添加身體和文檔屬性

+0

這看起來正是我所需要的。還有一個問題。 Visual Studio不提供給我一個createTextRange()函數。我想要做IHTMLTxtRange range = this.webBrowser.Document.Body.createTextRange();我是否混淆了你的「身體」財產正在返回。 – 2010-10-12 16:27:09

+0

我在答案中添加了Body和代碼。 – Timores 2010-10-12 19:22:08

+1

謝謝我發現了另一種讓我的代碼(createTextRange)工作的方法。所有其他代碼都非常有用。 findText標誌沒有按我期望的方式工作,但這本身就是一個問題。非常感謝!該代碼低於希望這可以幫助其他人。 IHTMLDocument2 htmlDoc =(IHTMLDocument2)webBrowser.Document.DomDocument; IHTMLBodyElement Body = htmlDoc.body as IHTMLBodyElement; IHTMLTxtRange range = Body.createTextRange(); – 2010-10-12 20:33:32

相關問題