TextBox controls in background forms for logging application events. Because the applications run for days at a time and many events are recorded, the
TextBoxes 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:
public void AppendTrace(string text, Color textcolor)
Int32 maxsize = 1024000;
Int32 dropsize = maxsize / 4;
if (richTextBox_RTCevents.Text.Length > maxsize)
Int32 endmarker = richTextBox_RTCevents.Text.IndexOf('\n', dropsize) + 1;
if (endmarker < dropsize)
endmarker = dropsize;
richTextBox_RTCevents.SelectionStart = richTextBox_RTCevents.Text.Length;
richTextBox_RTCevents.SelectionLength = 0;
richTextBox_RTCevents.SelectionColor = textcolor;
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
SelectionLength properties are reset prior to setting the
SelectionColor and appending the text; otherwise, the line added, sometimes, did not have the right color.
- March 11, 2009 - Original submission.