Writing colorized text to RichTextBox

You may have noticed I got carried away making everything a RichTextBox in the latest MDbg GUI. That's because I just like having some color in the world, and RichTextBox makes it very easy to colorize text. Here's a simple function to write a string to a RichTextBox in a given color.

        // Append text of the given color.
        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;
                // could set box.SelectionBackColor, box.SelectionFont too.
            }
box.SelectionLength = 0; // clear
        }

RTB colorizes by selecting a region of characters in the text box (via Select), and then calling the appropriate SelectionColor/BackColor/Font set methods. The key obstacle I saw was that the RTB's Text property doesn't roundtrip (bad design!) because it transforms things like "\r\n" into "\n" (There may be others: for example, we may wake up one day and find RTB gets an option to convert tabs to spaces). This means that (end-start) may not necessarily equal text.Length, and that confusion can throw off peoples calculations to the Select() method. However, we know that the the TextLength property must account for these encodings (whatever they may be), and so we can just calculate everything from that.

Here's an example of using the above snippet:

 
            AppendText(this.m_richTextBox1, Color.Empty, "empty");
            AppendText(this.m_richTextBox1, Color.Red, "AB\n\tCD");
            AppendText(this.m_richTextBox1, Color.Blue, "blue");

Which produces output that looks like:

     emptyAB
CDblue 

 

You can convert your existing TextBox objects in your winforms apps to a RichTextBox, and then throw some color in there! You could also colorize a RichTextBox by setting the RTF property, but handrolling your own RTF for formatting is going to be painful. This is much easier.

You can see I took advantage of this in several spots in the gui: The console text is colorized; and the IL/Source / active statements get colors too.