1. RichTextBox 控件概述
2. 创建WinForms项目
shell
dotnet new winforms -o LogUIApp
cd LogUIApp
3. 添加RichTextBox控件
4. 实现日志输出类
csharp
using System;
using System.Windows.Forms;
public class LogHelper
{
private RichTextBox _richTextBox;
public LogHelper(RichTextBox richTextBox)
{
_richTextBox = richTextBox;
}
public void Log(string message)
{
if (_richTextBox.InvokeRequired)
{
_richTextBox.Invoke(new MethodInvoker(() => Log(message)));
}
else
{
_richTextBox.AppendText(message + Environment.NewLine);
_richTextBox.ScrollToCaret(); // 自动滚动到底部
}
}
}
5. 在主窗体中使用LogHelper类
csharp
public partial class MainForm : Form
{
private LogHelper _logHelper;
public MainForm()
{
InitializeComponent();
_logHelper = new LogHelper(richTextBox1);
// 模拟日志输出
_logHelper.Log("应用程序启动");
_logHelper.Log("这是一条信息日志");
_logHelper.Log("这是一条错误日志", LogLevel.Error);
}
private void SimulateError()
{
try
{
// 模拟错误
throw new Exception("这是一个错误");
}
catch (Exception ex)
{
_logHelper.Log(ex.ToString(), LogLevel.Error);
}
}
}
public enum LogLevel
{
Info,
Error
}
6. 格式化日志输出
csharp
public void Log(string message, LogLevel logLevel = LogLevel.Info)
{
string logMessage = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} - {logLevel.ToString().ToUpper()} - {message}";
if (_richTextBox.InvokeRequired)
{
_richTextBox.Invoke(new MethodInvoker(() => Log(logMessage)));
}
else
{
_richTextBox.AppendText(logMessage + Environment.NewLine);
_richTextBox.ScrollToCaret();
}
}
7. 使用颜色区分日志级别
csharp
public void Log(string message, LogLevel logLevel = LogLevel.Info)
{
string logMessage = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} - {logLevel.ToString().ToUpper()} - {message}";
if (_richTextBox.InvokeRequired)
{
_richTextBox.Invoke(new MethodInvoker(() => Log(logMessage, logLevel)));
}
else
{
_richTextBox.SelectionStart = _richTextBox.TextLength;
_richTextBox.SelectionLength = 0;
switch (logLevel)
{
case LogLevel.Info:
_richTextBox.SelectionColor = Color.Black;
break;
case LogLevel.Error:
_richTextBox.SelectionColor = Color.Red;
break;
}
_richTextBox.AppendText(logMessage);
_richTextBox.SelectionColor = _richTextBox.ForeColor;
_richTextBox.ScrollToCaret();
}
}
8. 多线程环境下的日志输出
csharp
public void Log(string message, LogLevel logLevel = LogLevel.Info)
{
if (_richTextBox.InvokeRequired)
{
_richTextBox.Invoke(new MethodInvoker(() => Log(message, logLevel)));
}
else
{
var color = _richTextBox.SelectionColor;
_richTextBox.SelectionColor = logLevel == LogLevel.Error ? Color.Red : Color.Black;
_richTextBox.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} - {logLevel.ToString().ToUpper()} - {message}{Environment.NewLine}");
_richTextBox.SelectionColor = color;
_richTextBox.ScrollToCaret();
}
}
9. 实际应用
10. 结论
往期精品推荐: