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

WinForms 無閃爍跑馬燈控件實作:雙緩衝、區域刷新、Enabled 控制

     編輯:關於C#

專案來源與改進

基於 CodeProject ScrollingTextControl (jconwell) 進行三項關鍵改進:

  1. .NET 2.0+ 採用 OptimizedDoubleBuffer 取代已棄用的 DoubleBuffer。
  2. 刷新區域僅限可視範圍,避免長文字導致大區域無效化。
  3. 新增 Enabled 屬性覆寫,停用時暫停滾動。

核心改進代碼

1. 雙緩衝版本相容


Version v = Environment.Version;
if (v.Major < 2)
    SetStyle(ControlStyles.DoubleBuffer, true);
else
    SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true);

2. 精確刷新區域計算


private void Tick(object sender, EventArgs e)
{
    lastKnownRect.Inflate(10, 5); // 擴大文字邊界

    // 僅取與控件可視區交集
    RectangleF refreshRect = lastKnownRect;
    refreshRect.X = Math.Max(0, lastKnownRect.X);
    refreshRect.Width = Math.Min(lastKnownRect.Width + lastKnownRect.X, Width);
    refreshRect.Width = Math.Min(Width - lastKnownRect.X, refreshRect.Width);

    Invalidate(new Region(refreshRect));
    Update();
}

3. Enabled 屬性同步 Timer


[Browsable(true), Category("Behavior"), Description("控件是否啟用")]
new public bool Enabled
{
    set { timer.Enabled = value; base.Enabled = value; }
    get { return base.Enabled; }
}

完整控件代碼結構


public class ScrollingText : Control
{
    // 欄位:timer, text, scrollDirection, scrollPixelDistance, brushes, colors...
    // 屬性:TextScrollSpeed, TextScrollDistance, ScrollText, ScrollDirection, 
    //       VerticleTextPosition, ShowBorder, BorderColor, StopScrollOnMouseOver, Enabled
    // 事件:TextClicked (支援超連結式點擊)
    // 核心方法:DrawScrollingText, CalcTextPosition, EnableTextLink, OnPaint, Tick
}
public enum ScrollDirection { RightToLeft, LeftToRight, Bouncing }
public enum VerticleTextPosition { Top, Center, Bottom }

速度調節雙參數

屬性含義調大效果副作用
TextScrollSpeed (ms)Timer 間隔 = 重繪頻率越快CPU 佔用升高
TextScrollDistance (px)每幀位移像素越快過大則不連貫

實務上需**雙參數共同調整**尋找平衡點 (如 25ms + 2px)。

使用範例


var marquee = new ScrollingText();
marquee.ScrollText = "歡迎使用本系統!公告:系統維護時間...";
marquee.ScrollDirection = ScrollDirection.RightToLeft;
marquee.TextScrollSpeed = 30;
marquee.TextScrollDistance = 2;
marquee.StopScrollOnMouseOver = true;
marquee.TextClicked += (s,e) => Process.Start("https://example.com");
this.Controls.Add(marquee);

結語

透過 OptimizedDoubleBuffer、精確 Invalidate(Region)、Enabled 語意補全,將開源跑馬燈控件提升為生產可用等級。原始碼結構清晰,易於二次開發(加入圖片滾動、GIF 支援、右鍵選單等)。

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