Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Extend RichTextBox for Easy Formatted Appending

0.00/5 (No votes)
11 May 2015 1  
A few lines of code to make using the Windows Forms RichTextBox easier to use as a logging window.

Introduction

This tip suggests an extension method as a means of using the System.Windows.Forms.RichTextBox control as an appendable logging window.

Background

There are many controls suitable for logging windows (windows that display the ongoing state of a multi-step process such as installation). A multi-line scrolling TextBox can work fine, but lacks any colour, making it difficult to bring attention to problems.

A RichTextBox can do the trick, and works similarly to TextBox, however it poses some problems. To append some text, there is the AppendText method, but it cannot easily be formatted without some nitpicky work if you want to add any formatting.

Writing directly in RTF is not practical. There isn't an AppendRtf method, so you need to get and set the Rtf property each time you wish to update. This involves a lot of overhead, and wouldn't really work anyway due to the structure of RTF and the need for the document to have matching brace pairs.

I have implemented this functionality using an extension method that takes care of the verbose code required to format an appended line of text.

Extension Method

C#
using System;
using System.Drawing;
using System.Windows.Forms;

namespace RedCell.Windows.Forms
{
    /// <summary>
    /// RichTextBoxExtension adds the ability to easily append and format text.
    /// </summary>
    public static class RichTextBoxExtension
    {
        /// <summary>
        /// Appends the selection.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="text">The text.</param>
        public static void AppendSelection(this RichTextBox control, string text)
        {
            int len = control.TextLength;
           
            // Append the text.
            control.AppendText(text);

            // Prepare it for formatting.
            control.SelectionStart = len;
            control.SelectionLength = text.Length;

            // Scroll to it.
            control.ScrollToCaret();
        }

        /// <summary>
        /// Appends the selection.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="text">The text.</param>
        /// <param name="colour">The colour.</param>
        /// <param name="font">The font.</param>
        public static void AppendSelection(this RichTextBox control, string text, Color colour, Font font)
        {
            AppendSelection(control, text);
            control.SelectionColor = colour;
            control.SelectionFont = font;
        }

        /// <summary>
        /// Appends the selection.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="text">The text.</param>
        /// <param name="colour">The colour.</param>
        /// <param name="font">The font.</param>
        public static void AppendLog(this RichTextBox control, string text, Color colour, Font font)
        {
            Action append = () => AppendSelection(control, text, colour, font);
            if (control.InvokeRequired)
                control.Invoke(append);
            else
                append();
        }
    }
}

The AppendSelection method appends text to the end of the control, and leaves it in a selected state so that you can apply any additional formatting using the RichTextBox.Selection... properties.

There are two method signatures. The second is an example of further extending the method to be even more useful. You may wish to create your own to meet the formatting needs of your application.

The method AppendLog is an example of creating a logging method for your own needs. In this case, I am invoking on the UI thread if required, since actions that require logging often take place on a background thread.

Using the Code

Image 1

To use the code, instantiate your RichTextBox in the designer or in code, and start using it. A complete example might look like:

C#
public static void Main()
{
    // Make a form that contains a RichTextBox.
    var form = new Form {Width = 600, Height = 400};
    var rtb = new RichTextBox {Dock = DockStyle.Fill};
    form.Controls.Add(rtb);
    form.Show();

    // Define some styles.
    var success = Color.Green;
    var failure = Color.Red;
    var message = Color.DarkGray;
    var normal = rtb.Font;
    var bold = new Font(normal, FontStyle.Bold);

    // Just write some text.
    rtb.AppendLog("My logging window 1.0\r\n", message, normal);

    // Log an operation.
    try
    {
        // Open a file.
        rtb.AppendLog("Loading a file... ", message, normal);
        var file = System.IO.File.ReadAllText("happy.txt");
        rtb.AppendLog("SUCCESSFUL\r\n", success, bold);
    }
    catch (Exception ex)
    {
        rtb.AppendLog("FAILED: " + ex.Message + "\r\n", failure, bold);
    }
}

Conclusion

Using a simple extension method we bundled several lines of code required to implement a scrolling formatted text control into a no-need-to-think-about-it method.

History

  • Published May 11, 2015

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here