基於 CodeProject ScrollingTextControl (jconwell) 進行三項關鍵改進:
OptimizedDoubleBuffer 取代已棄用的 DoubleBuffer。Enabled 屬性覆寫,停用時暫停滾動。
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);
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();
}
[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 支援、右鍵選單等)。