简体   繁体   中英

How to programatically set RichTextbox text and line color?

I'm using this answer to programatically add colored lines to text to my RichTextBox.

My RichTextBoxExtensions class is exactly the same as the one in that solution. Then I have an OutputMessage class:

class OutputMessage
{
    private string _message;
    private Color _color;

    public string Message { get { return _message; } }
    public Color Color { get { return _color; } }

    public OutputMessage(string message, CodeDeployer.enums.OutputTypes ot)
    {
        _message = message;

        switch (ot)
        {
            case enums.OutputTypes.Success:
                _color = Color.Green;
                break;
            case enums.OutputTypes.Error:
                _color= Color.Red;
                break;
            case enums.OutputTypes.Warning:
                _color= Color.DarkOrange; 
                break;
            default:
                _color = Color.Black;
                break;
        }
    }
}

On my form, I maintain a List<OutputMessage> , then have a method that'll iterate over the List and try to put the contents into a RichTextBox on my form.

private void foo()
{
    this.txtOutput = GetOutput();
    this.txtOutput.Text = GetOutput().Text;
}

private RichTextBox GetOutput()
{
    RichTextBox results = new RichTextBox();

    foreach (OutputMessage om in output)
        results.AppendText(om.Message, om.Color);

    return results;
}

If I execute foo() with the first line of code, txtOutput doesn't change at all. It's just an empty textbox.

If I execute foo() with the second line of code, txtOutput does have all of the text from my List<OutputMessage> , however the color is lost.

If I change GetOutput to directly interact with the control on the form, it works as expected. Having it accept a RichTextBox as an argument works as well.

Can someone explain this to me? I'm guessing it has something to do with how things are passed by reference / by value, but I don't understand.

The .Text property of RichTextBox is plain unformatted text.

The Text property does not return any information about the formatting applied to the contents of the RichTextBox. To get the rich text formatting (RTF) codes, use the Rtf property.

So you should try using the .Rtf property instead:

this.txtOutput.Rtf = GetOutput().Rtf;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM