程序中的TextBox控件显示中文时出现乱码,表现为:
主要原因:使用了仅支持英文的字体(如Consolas、Courier New等)
// ❌ 错误:Consolas是英文字体,不支持中文
txtLog.Font = new Font("Consolas", 9);
次要原因:使用了Unix风格的换行符\n而非Windows风格的\r\n
// ⚠️ 不推荐:在Windows上应使用\r\n
txtLog.AppendText(message + "\n");
| 字体名称 | 特点 | 适用场景 |
|---|---|---|
| Microsoft YaHei (微软雅黑) | 现代、清晰、美观 | 通用场景(首选) |
| SimSun (宋体) | 传统、标准 | 正式文档 |
| SimHei (黑体) | 粗体、醒目 | 标题、强调 |
| KaiTi (楷体) | 书法风格 | 特殊效果 |
// ✅ 正确:使用微软雅黑字体
txtLog.Font = new Font("Microsoft YaHei", 9);
txtLog.ForeColor = Color.Black;
txtLog.BackColor = Color.White;
// ✅ 正确:使用系统默认字体(自动支持中文)
txtLog.Font = SystemFonts.DefaultFont;
// ✅ 高级:带字体回退机制
Font chineseFont = null;
string[] fontNames = { "Microsoft YaHei", "SimSun", "Arial Unicode MS" };
foreach (string fontName in fontNames)
{
try
{
Font testFont = new Font(fontName, 9);
// 检查字体是否可用
if (testFont.Name == fontName)
{
chineseFont = testFont;
break;
}
}
catch { }
}
if (chineseFont == null)
{
chineseFont = new Font(FontFamily.GenericSansSerif, 9);
}
txtLog.Font = chineseFont;
// 日志显示
txtLog = new TextBox();
txtLog.Multiline = true;
txtLog.ScrollBars = ScrollBars.Vertical;
txtLog.ReadOnly = true;
txtLog.Location = new Point(10, 190);
txtLog.Size = new Size(770, 360);
txtLog.Font = new Font("Consolas", 9); // ❌ 英文字体
// AppendLog方法
private void AppendLog(string message)
{
string timestamp = DateTime.Now.ToString("HH:mm:ss.fff");
txtLog.AppendText($"[{timestamp}] {message}\n"); // ❌ 字符串插值 + Unix换行符
}
// 日志显示
txtLog = new TextBox();
txtLog.Multiline = true;
txtLog.ScrollBars = ScrollBars.Vertical;
txtLog.ReadOnly = true;
txtLog.Location = new Point(10, 190);
txtLog.Size = new Size(770, 360);
// ✅ 使用支持中文的字体
txtLog.Font = new Font("Microsoft YaHei", 9);
txtLog.ForeColor = Color.Black;
txtLog.BackColor = Color.White;
// AppendLog方法
private void AppendLog(string message)
{
if (this.InvokeRequired)
{
this.Invoke(new Action<string>(AppendLog), message);
return;
}
string timestamp = DateTime.Now.ToString("HH:mm:ss.fff");
// ✅ 使用字符串拼接 + Windows换行符
txtLog.AppendText("[" + timestamp + "] " + message + "\r\n");
// 自动滚动到底部
txtLog.SelectionStart = txtLog.Text.Length;
txtLog.ScrollToCaret();
}
// ❌ 避免:设计器可能无法正确处理
txtLog.AppendText($"[{timestamp}] {message}");
// ✅ 推荐:使用简单字符串拼接
txtLog.AppendText("[" + timestamp + "] " + message);
// ✅ 正确:检查InvokeRequired
private void AppendLog(string message)
{
if (this.InvokeRequired)
{
this.Invoke(new Action<string>(AppendLog), message);
return;
}
// 更新UI代码
}
// 在程序中添加测试日志
AppendLog("CANopen从站测试程序已启动");
AppendLog("节点ID: 1");
AppendLog("中文测试:你好世界!");
AppendLog("特殊字符:@#$%^&*()");
AppendLog("混合文本:Node 1 状态正常");
[15:30:45.123] CANopen从站测试程序已启动
[15:30:45.125] 节点ID: 1
[15:30:45.126] 中文测试:你好世界!
[15:30:45.127] 特殊字符:@#$%^&*()
[15:30:45.128] 混合文本:Node 1 状态正常
所有中文字符应清晰显示,无乱码。
A: Consolas是微软开发的等宽英文字体,不包含中文字符的字形数据,因此无法正确显示中文。
A: 可以,只要该字体包含中文字符集。推荐使用:
A: 可能是因为:
A:
✅ 必须做:
\r\n作为换行符(Windows平台)❌ 避免做:
\n换行符🎯 推荐做法:
修复日期: 2026-05-09
修复内容: TextBox中文字体设置 + 换行符修正