首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# TextBox 多行模式:換行與自動捲動兩大常見問題解決

     編輯:關於C#

問題 1:多行 TextBox 如何正確換行?

Windows 系統換行序列為 \r\n (CRLF),單純用 `\n` 可能在某些控制項顯示異常。

解法 A:硬編碼 CRLF

string msg = "第一行\r\n第二行\r\n第三行";
textBox.AppendText(msg);

解法 B:跨平台相容 Environment.NewLine (推薦)

string msg = "第一行" + Environment.NewLine + "第二行";
textBox.AppendText(msg);
// 或
textBox.AppendText($"第一行{Environment.NewLine}第二行");

Environment.NewLine 在 Windows 回傳 `\r\n`,Linux/macOS 回傳 `\n`,確保跨平台 (如 Blazor Hybrid、MAUI) 正確顯示。

問題 2:新增文字後自動捲動到最新行

預設 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 補充

WPF `TextBox` 無 `ScrollToCaret()`,改用:


textBox.AppendText(text + Environment.NewLine);
textBox.ScrollToEnd(); // 需設定 VerticalScrollBarVisibility="Auto"

總結

需求WinFormsWPF
跨平台換行Environment.NewLineEnvironment.NewLine
自動捲動ScrollToCaret()ScrollToEnd()
非同步安全InvokeDispatcher.Invoke

掌握這兩個核心 API,即可輕鬆處理日誌視窗、即時訊息顯示等常見多行 TextBox 場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved