【问题标题】:Webbrowser find dialog for a text within an html elementWebbrowser 查找 html 元素中文本的对话框
【发布时间】:2015-04-28 13:42:43
【问题描述】:

我尝试在我的网络浏览器控件中使用查找对话框功能,它应该搜索几个单词(转发)并突出显示它们。 我尝试了this MSDN question的以下代码

    private bool FindFirst(string text)
    {
        IHTMLDocument2 doc = (IHTMLDocument2)browserInstance.Document;
        IHTMLSelectionObject sel = (IHTMLSelectionObject)doc.selection;
        sel.empty(); // get an empty selection, so we start from the beginning
        IHTMLTxtRange rng = (IHTMLTxtRange)sel.createRange();
        if (rng.findText(text, 1000000000, 0))
        {
            rng.select();
            return true;
        }
        return false;
    }

但是此代码和原始问题中的代码搜索整个文档并使用range = body.createTextRange() 创建一个范围,我想在特定元素内搜索(例如仅在特定div 中的文本)

我该怎么做?

【问题讨论】:

    标签: c# winforms search webbrowser-control textrange


    【解决方案1】:

    我通过在代码中添加moveToElementText(..) 解决了这个问题。它移动文本范围,使范围的开始和结束位置包含给定元素中的文本。

      bool FindFirst(HtmlElement elem, string text)
      {
            if (elem.Document != null)
            {
                IHTMLDocument2 doc =
                    elem.Document.DomDocument as IHTMLDocument2;
                IHTMLSelectionObject sel = doc.selection as IHTMLSelectionObject;
                sel.empty();
    
                IHTMLTxtRange rng = sel.createRange() as IHTMLTxtRange;
               // MoveToElement causes the search begins from the element
                rng.moveToElementText(elem.DomElement as IHTMLElement);
                if (rng.findText(text, 1000000000, 0))
                {
                    rng.select();
                    rng.scrollIntoView(true);
                    return true;
                }               
            }
            return false;
      }
       public bool FindNext(HtmlElement elem, string text)
        {
            if (elem.Document != null)
            {
                IHTMLDocument2 doc =
                    elem.Document.DomDocument as IHTMLDocument2;
                IHTMLSelectionObject sel = doc.selection as IHTMLSelectionObject;              
                IHTMLTxtRange rng = sel.createRange() as IHTMLTxtRange;
                rng.collapse(false);
                if (rng.findText(text, 1000000000, 0))
                {
                    rng.select();
                    rng.scrollIntoView(true);
                    return true;
                }
            }
            return false;
        }
    

    【讨论】:

      猜你喜欢
      • 2012-09-03
      • 2013-06-20
      • 2014-05-04
      • 1970-01-01
      • 2011-04-19
      • 2012-01-25
      • 2012-03-19
      相关资源
      最近更新 更多