【问题标题】:Change string color in rich text box if it contains X如果包含 X,则更改富文本框中的字符串颜色
【发布时间】:2013-03-17 04:02:20
【问题描述】:

我有一个提供输出的 Jar 文件和一个用于写入输出的富文本框。 Jar 文件给出的每个字符串都是富文本框中的一个新行。如果该行包含某些关键字,我想更改它的颜色。我尝试了以下方法:

if (textR.Contains("[INFO]"))
{
    //txtboxServerOutput.Text += textR + "\n";
    txtboxServerOutput.SelectedText = textR;
    txtboxServerOutput.SelectionColor = Color.Aqua;
}
else
{
    txtboxServerOutput.Text += textR + "\n";
}

这会导致输出混乱。富文本框对一些包含“[INFO]”的文本进行了着色,但不是全部,所有内容都是一行。我怎样才能解决这个问题?

【问题讨论】:

  • 你设置txtboxServerOutput.Multiline=true了吗?
  • @SrikanthVenugopalan 是的,当我只使用txtboxServerOutput.Text += textR + "\n"; 时,输出很好。

标签: c# windows winforms richtextbox


【解决方案1】:

我最终为 AppendText 创建了一个重载:

// Adds new overload for AppendText for rich textboxes
public static class RichTextBoxExtensions
{
        public static void AppendText(this RichTextBox txtbox, string text, Color color)
        {
            txtbox.SelectionStart = txtbox.TextLength;
            txtbox.SelectionLength = 0;

            txtbox.SelectionColor = color;
            txtbox.AppendText(text);
            txtbox.SelectionColor = txtbox.ForeColor;
        }
};

所以现在我可以这样做了:

richTextBox.AppendText("some random text", Color.Blue);

【讨论】:

    【解决方案2】:

    试试这个 -

    if (textR.Contains("[INFO]"))
    {
        txtboxServerOutput.SelectionColor = Color.Aqua;
    }
    txtboxServerOutput.SelectedText = textR + "\n";
    

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 2020-02-16
      • 1970-01-01
      • 2016-12-17
      • 2014-02-02
      • 2011-10-12
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      相关资源
      最近更新 更多