C# 中控制 RichTextBox 的长度
此技术在从 RichTextBox 控件中删除文本时,保留 RTF 格式。
引言
我使用 TextBox
控件在后台窗体中记录应用程序事件。由于应用程序运行时间长且记录了许多事件,因此需要修剪 TextBox
以避免使用过多内存。
最近,我切换到 RichTextBox
控件以便使用彩色文本,并发现我的修剪例程丢失了文本颜色和其他格式。这里介绍的方法解决了这个问题。
使用代码
这是我的新的日志记录例程
/// <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)
{
}
}
它的调用方式如下
AppendTrace("some text" + Environment.NewLine, Color.Blue);
关注点
在设置 SelectionColor
和追加文本之前,会重置 SelectionStart
和 SelectionLength
属性;否则,添加的行有时颜色不正确。
历史
- 2009年3月11日 - 原始提交。