如何将彩色字符串和其余字符串添加到 RichTextbox 中?

How can I add to a RichTextbox also the colored string and the rest of the string?

foreach(string line in lines)
{
    richTextBox1.AppendText(line);
    RichTextBoxExtensions.AppendText(richTextBox1, "Ready: ", Color.Red);
}

如果行是

"Hello world"

所以我想要的是 RichTextBox1 的第一行:

Ready Hello world

其中“Ready”仅显示红色“Ready”。

再下一行

Ready hi hello

再次准备就绪是红色的,但你好,它的原始颜色没有改变。

但我得到的是 mess the world Ready 被添加到行的末尾,并且它不只在第一行是红色的。

同样在 RichTextBox 中,所有行和 Ready 添加为文本块而不是行。

我想在RichTextBox中看到当运行程序是行:

Ready: Hello world
Ready: Hi hello
Ready: This is a line
Ready: Hi everyone

而且只有

Ready:

红色

public class RichTextBoxExtensions
{
    public static void AppendText(RichTextBox box, string text, Color color)
    {
        box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;

        box.SelectionColor = color;
        box.AppendText(text);
        box.SelectionColor = box.ForeColor;
    }
    public static void UpdateText(RichTextBox box, string find, string replace, Color? color)
    {
        box.SelectionStart = box.Find(find, RichTextBoxFinds.Reverse);
        box.SelectionLength = find.Length;
        box.SelectionColor = color ?? box.SelectionColor;
        box.SelectedText = replace;
    }
}

也许你可以这样做

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        richTextBox1.Font = new Font("Consolas", 18f, FontStyle.Bold);
        richTextBox1.BackColor = Color.AliceBlue;
        string[] words =
        {
            "a",
            "b",
            "c",
            "d",
            "e",
            "f",
            "g."
        };
        Color[] colors =
        {
            Color.Aqua,
            Color.CadetBlue,
            Color.Cornsilk,
            Color.Gold,
            Color.HotPink,
            Color.Lavender,
            Color.Moccasin
        };
        for (int i = 0; i < words.Length; i++)
        {
            string word = words[i];
            Color color = colors[i];
            {
                richTextBox1.SelectionBackColor = color;
                richTextBox1.AppendText(word);
                richTextBox1.SelectionBackColor = Color.AliceBlue;
                richTextBox1.AppendText(" ");
            }
        }
    }
}

}

反转 for-loop 中的 2 行代码,然后添加 Environment.NewLine。 这个小修正:

foreach (string line in lines)
{
    RichTextBoxExtensions.AppendText(richTextBox1, "Ready: ", Color.Red);
    richTextBox1.AppendText(line + Environment.NewLine);
}

用这个列表测试它:

List<string> lines = new List<string>() { "Hello world", "hi hello", "this is a line"};

得出这个结果: