如何在richtextbox中使用多种颜色

Bil*_*lie 14 .net c# richtextbox

我使用C#windows窗体,我有richtextbox,我想用红色标记一些文本,一些用绿色,一些用黑色.

怎么办?附图.

在此输入图像描述

Pic*_*are 30

System.Windows.Forms.RichTextBox有一个Color名称类型的属性,SelectionColor用于获取或设置当前选择或插入点的文本颜色.您可以使用此属性使用RichTextBox指定的颜色标记您的特定字段.

RichTextBox _RichTextBox = new RichTextBox(); //Initialize a new RichTextBox of name _RichTextBox
_RichTextBox.Select(0, 8); //Select text within 0 and 8
_RichTextBox.SelectionColor = Color.Red; //Set the selected text color to Red
_RichTextBox.Select(8, 16); //Select text within 8 and 16
_RichTextBox.SelectionColor = Color.Green; //Set the selected text color to Green
_RichTextBox.Select(0,0); //Select text within 0 and 0
Run Code Online (Sandbox Code Playgroud)

注意:您可以通过避免使用计算RichTextBox.Find(string str)可通过添加Object Browser,如果你想突出内的文本LinesRichTextBox赋予它的价值

RichTextBox _RichTextBox = new RichTextBox(); //Initialize a new RichTextBox of name _RichTextBox
_RichTextBox.Find("Account 12345, deposit 100$, balance 200$"); //Find the text provided
_RichTextBox.SelectionColor = Color.Green; //Set the selected text color to Green
Run Code Online (Sandbox Code Playgroud)

谢谢,
我希望你觉得这很有帮助:)


Mar*_*ram 13

我找到了这种扩展方法,使您能够更改字符串的颜色以及插入换行值:

    public static void AppendText(this RichTextBox box, string text, Color color, bool AddNewLine = false)
    {
        if (AddNewLine)
        {
            text += Environment.NewLine;
        }

        box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;

        box.SelectionColor = color;
        box.AppendText(text);
        box.SelectionColor = box.ForeColor;
    }
Run Code Online (Sandbox Code Playgroud)