如何在 WebBrowser 控件 C# 中突出显示特定单词 [英] How to Highlight a specific word in WebBrowser control C#

查看:21
本文介绍了如何在 WebBrowser 控件 C# 中突出显示特定单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 webbrowser 控件,我能够获取用户选择的单词.我将这个词保存在一个文件中,同时我也保存了它的字节偏移量和长度.

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.

假设我的 Web 浏览器控件中有一些文本,例如Hello Hey Hello",假设用户选择了最后一个 hello.

Lets says i have some text in my Web browser control as "Hello Hey Hello" lets say the user has selected last hello.

现在这个词和其他信息一起保存了,比如它的长度等.

Now that word is saved with me along with other info like its length etc.

当用户重新加载文件并向我发送该词及其长度和字节偏移量时,我需要提供一个功能来突出显示所选词

I need to provide a feature to highlight the selected word when the user reloads the file and sends me that word along with its length and byte offset

有什么办法吗.

推荐答案

如果你还没有,你将需要导入 Microsoft.mshtml 程序集引用,并添加

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();
                   }
                }
            }
        }

这篇关于如何在 WebBrowser 控件 C# 中突出显示特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆