Color Rich TextBox C# windows 表单

Color Rich TextBox C# windows forms

我有一个多线程应用程序,richtextbox 是从另一个 thread 更新的,而不是创建它的那个:Form1 所以我使用了委托技巧来做到这一点:

delegate void SetTextCallback(string text);
    public static void SetText(String text)
    {
        if (Form1.myform.richtextbox.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            Form1.myform.richtextbox.Invoke(d, new object[] { text });
        }
        else
        {
            Form1.myform.richtextbox.AppendText(text);
        }
    }

问题:如何给这个 text 上色?

您必须使用 Select Method on the RichTextBox after you append your text to select it (use TextLenght to find the range to select). Then you could use SelectionColor Property 来更改颜色。

当然这应该在 UI 线程上完成。

public void SetText(string text, Color color)
{
    if (this.RichTextBox1.InvokeRequired) {
        SetTextCallBack d = new SetTextCallBack(SetText);
        this.Invoke(d, {
            text,
            color
        });
    } else {
        int length = this.RichTextBox1.TextLength;
        this.RichTextBox1.AppendText(text);
        this.RichTextBox1.Select(length, text.Length);
        this.RichTextBox1.SelectionColor = color;
    }
}

我已经使用这些虚拟任务对其进行了测试。

private void StartServer
{
    Task y = new Task(() => this.SetText("Yellow Text", Color.Yellow));
    Task z = new Task(() => this.SetText("Red Text", Color.Red));
    y.Start();
    z.Start();
}