How Do I programatically select text in a webBrowser Control? c#

我只是一个虾纸丫 提交于 2019-12-06 06:37:03

问题


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 having 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?


回答1:


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



来源:https://stackoverflow.com/questions/3915871/how-do-i-programatically-select-text-in-a-webbrowser-control-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!