簡體   English   中英

如何在richTextBox中為文本的特定部分着色?

[英]How do i color a specific part of text in a richTextBox?

private void LoadKeys(Dictionary<string,List<string>> dictionary, string FileName)
        {
           string line = System.String.Empty;
           using (StreamReader sr = new StreamReader(keywords))
           {
            while ((line = sr.ReadLine()) != null)
            {
                string[] tokens = line.Split(',');
                dictionary.Add(tokens[0], tokens.Skip(1).ToList());
                richTextBox2.AppendText("Url: " + tokens[0] + " --- " + "Localy KeyWord: " + tokens[1]+Environment.NewLine);
                ColorText(richTextBox2, Color.Red);
            }
           } 
        }

和函數ColorText:

public void ColorText(RichTextBox box, Color color)
        {
            box.SelectionStart = box.TextLength; box.SelectionLength = 0;
            box.SelectionColor = color;
            box.SelectionColor = box.ForeColor;
        } 

但是它沒有使紅色變色。 沒有改變。 我希望能夠以紅色為唯一顏色,例如僅標記[0]和綠色[1]。

我該怎么做 ?

public void ColorText(RichTextBox box, Color color)
        {
            box.Select(start, 5);
            box.SelectionColor = color;
        } 

您在ColorText中顯示的代碼將顯示到文本的末尾,將選擇長度設置為0,將顏色設置為紅色,然后又恢復為原色,因此無法實現。

也許您需要做類似的事情

        box.Text = "This is a red color";
        box.SelectionStart = 10;
        box.SelectionLength = 3;
        box.SelectionColor = Color.Red;
        box.SelectionLength = 0;

box.SelectionStart = box.TextLength; -您代碼的這一行可以解釋為“從方框文本的末尾開始突出顯示文本”。 即不選擇任何文本,因為在最后一個文本之后不能再有任何文本。

box.SelectionLength = 0; -更進一步,此行可以解釋為“突出顯示0個文本”。 您已經兩次確定未選擇任何文字哈哈。

我不確定您要如何確定要選擇的文本,但是我會使用類似以下的內容:

        public void ColorSelectedText(RichTextBox textBox, Int32 startPos, Int32 length, Color color)
        {
            textBox.Select(startPos, length);
            textBox.SelectionColor = color;
        } 

傳遞您的文本框對象和顏色。

您傳遞的整數可以認為就像您用鼠標光標突出顯示了文本一樣:

startPos是單擊鼠標的位置,“ length”是startPos與釋放鼠標之間的字符數。

暫無
暫無

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

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