double offsetDebug = 0;
int maxLines = 300;
void ShowLog(string msg, Brush color)
{
this.Dispatcher.BeginInvoke(DispatcherPriority.SystemIdle, (ThreadStart)delegate ()
{
string s = string.Format("{0}:[{1}]", DateTime.Now, msg);
Paragraph p = new Paragraph(new Run(s));
p.FontSize = 14;
p.LineHeight = 3;
p.Foreground = color;
rtb_Msg.Document.Blocks.Add(p);
needAutoScroll(rtb_Msg, ref offsetDebug);
if (rtb_Msg.Document.Blocks.Count > maxLines)
for (int i = maxLines; i < rtb_Msg.Document.Blocks.Count; i++)
{
rtb_Msg.Document.Blocks.Remove(rtb_Msg.Document.Blocks.FirstBlock);
}
});
}
bool needAutoScroll(RichTextBox rich, ref double offset)
WPF RichTextBox追加文本并设置颜色
最新推荐文章于 2025-06-26 09:22:29 发布
本文介绍了一个使用C#实现的日志显示功能,通过Dispatcher.BeginInvoke进行UI线程安全调用,将带有时间戳的消息添加到RichTextBox中,并实现了自动滚动功能,确保最新消息始终可见。同时,为保持日志数量在限定范围内,当超出最大行数时会移除最早的消息。

2073

被折叠的 条评论
为什么被折叠?



