【问题标题】:Highlight selected hybrid text in C# webBrowser control在 C# webBrowser 控件中突出显示选定的混合文本
【发布时间】:2016-04-13 18:23:00
【问题描述】:

作为this suggestion,我正在使用以下代码在 webBrowser 中突出显示选定的文本:

using mshtml;

    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)
            {
                string oldText = range.text.Replace("\n", "</br>");
                string newHtmlText = "<span style='background-color: rgb(255, 255, 0);'>" +oldText + "</span>";                        
                range.pasteHTML(newHtmlText);                        
            }
        }
    }

When a normal text is selected every thing is OK.但是,在选择某些混合文本时,您可以在此图像中看到,它将损坏文档。

有时选定的文本可能包含表格和其他格式的文本。如何在不更改格式的情况下突出显示文档的任何部分?

【问题讨论】:

    标签: c# html .net webbrowser-control highlighting


    【解决方案1】:

    我找到了答案。

    mshtml 具有管理文本的完整选项。 Here 是 execCommand 的语法,用于对文档进行任何更改。

    这样你就不需要自己解析 html 或者知道 html 元素了。

    using mshtml;
    
    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)
            {
                range.execCommand("BackColor", false, "FFFF00");                      
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-27
      • 2011-08-02
      • 2017-07-14
      • 2019-12-27
      • 2020-12-24
      • 1970-01-01
      • 2010-10-29
      • 2014-03-30
      相关资源
      最近更新 更多