How to Highlight a specific word in WebBrowser control C#

后端 未结 2 1977
猫巷女王i
猫巷女王i 2021-02-08 17:35

I have a webbrowser control and I am able to get the selected word by the user. I am saving this word in a file and with it I am also saving its byte offset and length.

2条回答
  •  走了就别回头了
    2021-02-08 18:02

    you're going to need to import the Microsoft.mshtml assembly reference if you haven't already, and add

    using mshtml;
    
            if (webBrowser1.Document != null)
            {
                IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2;
                if (document != null)
                {
                    IHTMLBodyElement bodyElement = document.body as IHTMLBodyElement;
                    if (bodyElement != null)
                    {
                        IHTMLTxtRange trg = bodyElement.createTextRange();
    
    
                        if (trg != null)
                        {
                            const String SearchString = "Privacy"; // This is the search string you're looking for.
                            const int wordStartOffset = 421; // This is the starting position in the HTML where the word you're looking for starts at.
                            int wordEndOffset = SearchString.Length;
                            trg.move("character", wordStartOffset);
                            trg.moveEnd("character", wordEndOffset);
    
                            trg.select();
                        }
                    }
                }
            }
    

    here is a snippet that might be helpful also:

            if (webBrowser1.Document != null)
            {
                IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2;
                if (document != null)
                {
                    IHTMLSelectionObject currentSelection = document.selection;
    
                    IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
                    if (range != null)
                    {
                       const String search = "Privacy";
    
                       if (range.findText(search, search.Length, 2))
                       {
                           range.select();
                       }
                    }
                }
            }
    

提交回复
热议问题