Search code examples
c#colorsrichtextboxbold

c# Rich text box coloring and bolding


I'm quite new in C# but, I want to make myself a debug console in form dbg. And I want to color and bold the variables that are coming for it, I made an function to easy write to console:

    private void writtodbg(string x, string y)
    {
        string a = Convert.ToString(x);
        string b = Convert.ToString(y);

        Debug.rTB1.AppendText(a, Color.Orange); // bold
        Debug.rTB1.AppendText(" = "); // bold
        Debug.rTB1.AppendText(b + Environment.NewLine, Color.Orange); // bold

    }

But then error occurs which says "No overload for method 'AppendText' takes 2 arguments".


Solution

  • That's because AppendText() can only receive a String. You can't specify the Color. If you're seeing code from somewhere online that has syntax like that then it is probably a custom RichTextBox class where someone has added that ability.

    Try something like this:

        private void writtodbg(string x, string y)
        {
            AppendText(x, Color.Orange, true);
            AppendText(" = ", Color.Black, false);
            AppendText(y + Environment.NewLine, Color.Orange, true);
        }
    
        private void AppendText(string text, Color color, bool bold)
        {
            Debug.rTB1.SelectionStart = Debug.rTB1.TextLength;
            Debug.rTB1.SelectionColor = color;
            Debug.rTB1.SelectionFont = new Font(Debug.rTB1.Font, bold ? FontStyle.Bold : FontStyle.Regular);
            Debug.rTB1.SelectedText = text;
        }