Windows 系統換行序列為 \r\n (CRLF),單純用 `\n` 可能在某些控制項顯示異常。
string msg = "第一行\r\n第二行\r\n第三行";
textBox.AppendText(msg);
Environment.NewLine (推薦)string msg = "第一行" + Environment.NewLine + "第二行";
textBox.AppendText(msg);
// 或
textBox.AppendText($"第一行{Environment.NewLine}第二行");
Environment.NewLine 在 Windows 回傳 `\r\n`,Linux/macOS 回傳 `\n`,確保跨平台 (如 Blazor Hybrid、MAUI) 正確顯示。
預設 TextBox 不會自動捲動,需呼叫 ScrollToCaret()。
textBox.AppendText(newContent + Environment.NewLine);
textBox.ScrollToCaret(); // 捲動至游標 (AppendText 後游標在尾端)
public static class TextBoxExtensions
{
///
/// 附加文字並自動捲動至底部
///
public static void AppendLineAndScroll(this TextBox tb, string text)
{
if (tb == null) throw new ArgumentNullException(nameof(tb));
tb.AppendText(text + Environment.NewLine);
tb.ScrollToCaret();
}
///
/// 非 UI 執行緒安全版本 (WinForms/WPF)
///
public static void AppendLineAndScrollThreadSafe(this TextBox tb, string text)
{
if (tb.InvokeRequired)
{
tb.Invoke(new Action(() => tb.AppendLineAndScroll(text)));
}
else
{
tb.AppendLineAndScroll(text);
}
}
}
public static void AppendLineWithLimit(this TextBox tb, string text, int maxLines = 1000)
{
tb.AppendText(text + Environment.NewLine);
if (tb.Lines.Length > maxLines)
{
// 移除最舊的行
var lines = tb.Lines;
Array.Copy(lines, lines.Length - maxLines, lines, 0, maxLines);
tb.Lines = lines;
}
tb.ScrollToCaret();
}
WPF `TextBox` 無 `ScrollToCaret()`,改用:
textBox.AppendText(text + Environment.NewLine);
textBox.ScrollToEnd(); // 需設定 VerticalScrollBarVisibility="Auto"
| 需求 | WinForms | WPF |
|---|---|---|
| 跨平台換行 | Environment.NewLine | Environment.NewLine |
| 自動捲動 | ScrollToCaret() | ScrollToEnd() |
| 非同步安全 | Invoke | Dispatcher.Invoke |
掌握這兩個核心 API,即可輕鬆處理日誌視窗、即時訊息顯示等常見多行 TextBox 場景。