How to programmatically select text in a web browser control? WITH#

Here's the problem: I want a user of my program to search for the webBrowser control for this keyword (standard Ctrl + F). I have no problem finding a keyword in a document and highlighting all instances using the span and replace () function. I am facing the problem of getting the next function that I want to work. When the user clicks the Find Next button, I want the document to scroll to the next instance. If I could get a bounding box, I could use the navigation function. I have the same functionality working in a rich text field 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 someone provide a methodology to make this work in webBrowser?

+3
source share
1 answer

I implemented a search function in a WinForms application with a built-in web browser. He had a separate text field for entering the search string and the Find button. If the search bar has changed since the last search, pressing the button means a normal find, and if not, it means "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: body and document properties added

+1
source

Source: https://habr.com/ru/post/1769163/


All Articles