【问题标题】:How to use multi color in richtextbox [duplicate]如何在richtextbox中使用多色[重复]
【发布时间】:2012-10-24 14:59:33
【问题描述】:

我使用 C# windows 窗体,并且我有richtextbox,我想将一些文本着色为红色、一些绿色和一些黑色。

怎么做?附图片。

【问题讨论】:

  • 一些显示你已经做过的代码会很有帮助。
  • @PaulHiemstra 事实上,我是一名 C++、C、Java、Assembly 和更多语言程序员,我以前从未使用过 C#。我在拼贴中上了一门关于 C# 的课程。 '在我进入这个行业之前,我可能需要你的帮助。感谢您的收听。
  • 我希望这里是您正在寻找的解决方案stackoverflow.com/a/27149285/998483

标签: c# .net richtextbox


【解决方案1】:

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

注意:如果您想在RichTextBox 中突出显示Lines 中的文本并赋予其值,则可以使用RichTextBox.Find(string str) 来避免计算,可以通过Object Browser 添加它

示例

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

谢谢,
希望对您有所帮助:)

【讨论】:

【解决方案2】:

我发现这个扩展方法可以让您更改字符串的颜色以及插入换行符值:

    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;
    }

【讨论】:

  • 我想你也可以在方法的开头加上box.SuspendLayout(),在最后加上box.ResumeLayout()
【解决方案3】:

您可以使用 Run 对象在运行时更改颜色

private Run GetForegroundColor(string strInformation, Brush color)
        {
            Run noramlRun = new Run(strInformation);
            noramlRun.Foreground = color;
            return noramlRun;
        }

对于更复杂的场景,例如根据要求更改颜色,然后访问打击链接

https://sites.google.com/site/greateindiaclub/mobil-apps/windows8/customwpfrichtextboxwithcolorchangeandhighlightfunctionality

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 2011-07-20
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多