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

WinForms TextBox 實現無縫循環自動捲動效果

     編輯:關於C#

需求場景

在日誌視窗、監控介面中,需讓 TextBox 內容自動向上捲動,到達底部後無縫循環回到頂部,滑鼠進入時暫停,離開繼續。

核心實作

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication27
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // 初始化測試資料
            for (int i = 0; i <= 20; i++)
                textBox1.Text += $"{i}:jinjazz__{i} ";

            timer1.Interval = 200;
            timer1.Start();
        }

        // Win32 API
        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);

        [DllImport("user32.dll")]
        public static extern int GetScrollPos(IntPtr hwnd, int nBar);

        [DllImport("user32.dll")]
        static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw);

        const int EM_LINESCROLL = 0xB6; // 垂直捲動一行

        private void timer1_Tick(object sender, EventArgs e)
        {
            int posBefore = GetScrollPos(textBox1.Handle, 1); // SB_VERT = 1

            // 向下捲動一行
            SendMessage(textBox1.Handle, EM_LINESCROLL, 0, 1);

            // 若捲動條位置未變化,表示已到達底部
            if (posBefore == GetScrollPos(textBox1.Handle, 1))
            {
                // 回到頂部:SetScrollPos 文字與捲動條不同步,改用選取游標法
                textBox1.SelectionStart = 0;
                textBox1.SelectionLength = 1;
                textBox1.ScrollToCaret();
                textBox1.SelectionLength = 0;
            }
        }

        private void textBox1_MouseEnter(object sender, EventArgs e) => timer1.Stop();
        private void textBox1_MouseLeave(object sender, EventArgs e) => timer1.Start();
    }
}

關鍵技術點

  1. EM_LINESCROLL (0xB6):傳送訊息讓 TextBox 捲動指定行數,wParam=0, lParam=1 表示垂直向下一行。
  2. GetScrollPos / SetScrollPos:讀取/設定捲動條位置。但 SetScrollPos 僅移動捲動條,不帶動文字,故不採用。
  3. ScrollToCaret():將游標捲動至可見區域,配合 SelectionStart=0 實現跳回頂部。
  4. 滑鼠互動:MouseEnter/Leave 控制 Timer 啟停,提升使用者體驗。

優化建議

  • 使用 RichTextBox 可支援彩色日誌、RTF 格式。
  • 大量資料時考慮虛擬化(僅渲染可見行)或定期清理舊內容,避免記憶體無限增長。
  • 若需水平捲動,改用 SB_HORZ = 0 與 EM_LINESCROLL 的 wParam 參數。

結語

結合 Win32 訊息與 TextBox 原生方法,即可實現流暢、可控的循環捲動效果,適合即時日誌、跑馬燈等場景。

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