首页 > 解决方案 > 我可以使用这段旧代码来更改富文本框中一行的文本颜色吗?

问题描述

在不存在错误的情况下,RichTextBox 字段中的文本颜色不会改变。

这是一个简单的基于文本的 c# 游戏(我很新)。我在网上尝试了多种不同的解决方案,但无济于事。我发现这个 2006 年的旧代码似乎没有错误但似乎没有改变任何东西。我假设发生故障的地方是文本实际上并没有被选中,尽管语法似乎是正确的。我尝试以读取文本长度的形式插入一些调试代码,它给出了正确的数字——在这个例子中,选择长度显示为 26,这是正确的。

void AppendText(RichTextBox box, Color color, string text)
    {
        int start = box.TextLength;
        box.AppendText(text);
        int end = box.TextLength;

        //Textbox may transform chars, so (end-start) != text.Length
        box.Select(start, end - start);
        {
            box.SelectionColor = color;
        }
        box.SelectionLength = 0;
        box.Text += Environment.NewLine;
    }

//which is being called by:

AppendText(rtbMessages, Color.Red, "Yarr Matey, this be a test");

我希望它将此文本更改为红色。它不会改变文本颜色。

有趣的是,如果(而不是 box.SelectionColor)插入 box.Forecolor,它确实会将整个文本框更新为红色 - 让我相信选择部分是断开的链接。

运行此代码时不存在错误。

标签: c#richtextbox

解决方案


我读到使用+=附加文本会重置所有应用的颜色,所以无论您的代码的早期部分可能取得成功,它们很可能会被最后一行抹去!

我在评论中链接了一个相关的 SO 问题;它似乎与您的大致相似,但 225 多人似乎很欣赏它的工作原理。它是一种扩展方法,因此您需要在静态类中声明它,但随后它就可以在您拥有的任何 RichTextBox 上巧妙地使用..


编辑:所以您说它有效,但您不期待更改所有代码

我猜你的代码是这样的:

AppendText(rtbMessages, Color.Red, "Yarr Matey, this be a test");
AppendText(rtbMessages2, Color.Blue, "Yarr Matey, this be a test 2");
AppendText(rtbMessages3, Color.Green, "Yarr Matey, this be a test 3");

要么改变你的 AppendText 方法(他们都在调用),所以它调用扩展:

public static class RichTextBoxExtensions
{
  //this is THE EXTENSION method
  public static void AppendText(this RichTextBox box, string text, Color color)
  {
    ...
  }
}


//this is YOUR code
void AppendText(RichTextBox box, Color color, string text)
{
    //call THE EXTENSION code
    box.AppendText(color, text);
}

//now your code, calls your code, calls the extension
AppendText(rtbMessages, Color.Red, "Yarr Matey, this be a test");

或者在您的代码中运行查找替换:

FIND: AppendText\((\w+), (.*)
REPL: $1.AppendText($2)


AppendText(rtbMessages, Color.Red, "Yarr Matey, this be a test");
           ^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
               $1                        $2

它将转换您的所有代码:

FROM: AppendText(rtb1, color, text);
TO:   rtb1.AppendText(color, text);

推荐阅读