簡體   English   中英

在C#webBrowser控件中突出顯示選定的混合文本

[英]Highlight selected hybrid text in C# webBrowser control

作為此建議,我正在使用以下代碼突出顯示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);                        
            }
        }
    }

當選擇普通文本時,一切正常。 但是,如您在該圖像中看到的那樣,當選擇了某些混合文本時,它將損壞文檔。

在此處輸入圖片說明

有時,所選文本可能包含表格和其他格式的文本。 如何在不更改格式的情況下突出顯示文檔的任何部分?

我找到了答案。

mshtml具有管理文本的完整選項。 是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");                      
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM