Click here to Skip to main content
15,885,278 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Extend RichTextBox for Easy Formatted Appending

Rate me:
Please Sign up or sign in to vote.
4.94/5 (10 votes)
11 May 2015CPOL2 min read 22.8K   13   2
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer Robotic Assistance Devices / AITX
Canada Canada
Yvan Rodrigues has 30 years of experience in information systems and software development for the industry. He is Senior Concept Designer at Robotic Assistance Devices

He is a Certified Technician (C.Tech.), a professional designation granted by the Institute of Engineering Technology of Ontario (IETO).

Yvan draws on experience as owner of Red Cell Innovation Inc., Mabel's Labels Inc. as Manager of Systems and Development, the University of Waterloo as Information Systems Manager, and OTTO Motors as Senior Systems Engineer and Senior Concept Designer.

Yvan is currently focused on design of embedded systems.

Comments and Discussions

 
GeneralNice! Pin
Ravi Bhavnani11-May-15 11:54
professionalRavi Bhavnani11-May-15 11:54 
AnswerRe: Nice! Pin
Yvan Rodrigues11-May-15 14:18
professionalYvan Rodrigues11-May-15 14:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.