Controlling the Length of a RichTextBox in C#
This technique preserves RTF formatting when removing text from a RichTextBox control.
Introduction
I use TextBox
controls in background forms for logging application events. Because the applications run for days at a time and many events are recorded, the TextBox
es need to be pruned to avoid using too much memory.
Recently, I switched to RichTextBox
controls so I could use colored text, and found that my trim routine lost the text colors and other formatting. The method presented here solves that problem.
Using the code
Here is my new logging routine:
/// <summary>
/// timestamp the message and add to the textbox.
/// To prevent runtime faults should the amount
/// of data become too large, trim text when it reaches a certain size.
/// </summary>
/// <param name="text"></param>
public void AppendTrace(string text, Color textcolor)
{
// keep textbox trimmed and avoid overflow
// when kiosk has been running for awhile
Int32 maxsize = 1024000;
Int32 dropsize = maxsize / 4;
if (richTextBox_RTCevents.Text.Length > maxsize)
{
// this method preserves the text colouring
// find the first end-of-line past the endmarker
Int32 endmarker = richTextBox_RTCevents.Text.IndexOf('\n', dropsize) + 1;
if (endmarker < dropsize)
endmarker = dropsize;
richTextBox_RTCevents.Select(0, endmarker);
richTextBox_RTCevents.Cut();
}
try
{
// trap exception which occurs when processing
// as application shutdown is occurring
richTextBox_RTCevents.SelectionStart = richTextBox_RTCevents.Text.Length;
richTextBox_RTCevents.SelectionLength = 0;
richTextBox_RTCevents.SelectionColor = textcolor;
richTextBox_RTCevents.AppendText(
System.DateTime.Now.ToString("HH:mm:ss.mmm") + " " + text);
}
catch (Exception ex)
{
}
}
It is called like this:
AppendTrace("some text" + Environment.NewLine, Color.Blue);
Points of Interest
The SelectionStart
and SelectionLength
properties are reset prior to setting the SelectionColor
and appending the text; otherwise, the line added, sometimes, did not have the right color.
History
- March 11, 2009 - Original submission.