Here's the Problem: I want to enable the user of my program to search a webBrowser control for a given keyword (standard Ctrl+ F). I am havi开发者_如何学运维ng no problem finding the keyword in the document and highlighting all the instances using a span and the replace() function. I am having trouble getting the "find next" functionlity that I want to work. When the user clicks Find next I want the document to scroll to the next instance. If I could get a bounding box I can use the navigate function. I have this same functionality working in a rich text box using the following code
//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();
Can anyone provide a methodology to get this to work in a webBrowser?
I implemented a search feature in a WinForms app that had an embedded Web browser control. It had a separate text box for entering a search string and a 'Find' button. If the search string had changed since the last search, a button click meant a regular find, if not, it meant 'find again'. Here is the button handler:
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 is set to true in the TextChanged handler of the search box.
Hope this helps.
Edit: added Body and Document properties
精彩评论