如何在RichTextBox中实现循环加载圆点动画效果?
RichTextBox 循环圆点加载动画实现(WinForm)
核心实现思路:用定时器按固定间隔循环切换圆点数量,通过局部选中文本替换的方式更新内容,避免全量重绘带来的闪烁问题,动画循环逻辑为3点→2点→1点→2点→3点往复。
前置字段定义
先在窗体类内声明动画所需的全局变量,避免定时器触发时状态丢失:// 加载状态固定前缀 private const string LoadingTextPrefix = "Loading"; // 当前显示的圆点数量,初始值为3 private int _currentDotCount = 3; // 圆点数量变化方向标记:true为逐次减少,false为逐次增加 private bool _dotCountDecreasing = true; // 动画控制定时器 private readonly System.Windows.Forms.Timer _animationTimer = new System.Windows.Forms.Timer();动画启动逻辑
调用该方法即可在目标RichTextBox中启动加载动画,定时器间隔设为300ms时动画流畅度最佳:private void StartDotLoading() { // 初始化文本 richTextBoxTarget.SuspendLayout(); richTextBoxTarget.Clear(); richTextBoxTarget.AppendText($"{LoadingTextPrefix}{new string('.', _currentDotCount)}"); richTextBoxTarget.ResumeLayout(); // 绑定定时器事件并启动 _animationTimer.Interval = 300; _animationTimer.Tick -= AnimationTimer_Tick; _animationTimer.Tick += AnimationTimer_Tick; _animationTimer.Start(); }定时器帧更新逻辑
每次定时器触发时更新圆点计数,仅替换文本末尾的圆点部分,不重写全量内容:private void AnimationTimer_Tick(object sender, EventArgs e) { // 更新圆点计数与变化方向 if (_dotCountDecreasing) { _currentDotCount--; if (_currentDotCount == 1) _dotCountDecreasing = false; } else { _currentDotCount++; if (_currentDotCount == 3) _dotCountDecreasing = true; } // 局部更新文本防闪烁 richTextBoxTarget.SuspendLayout(); richTextBoxTarget.SelectionStart = LoadingTextPrefix.Length; richTextBoxTarget.SelectionLength = richTextBoxTarget.TextLength - LoadingTextPrefix.Length; richTextBoxTarget.SelectedText = new string('.', _currentDotCount); // 重置光标位置避免选中状态残留 richTextBoxTarget.SelectionStart = richTextBoxTarget.TextLength; richTextBoxTarget.SelectionLength = 0; richTextBoxTarget.ResumeLayout(); }动画停止逻辑
加载完成后调用该方法停止定时器,清理加载文本即可:private void StopDotLoading() { _animationTimer.Stop(); _animationTimer.Tick -= AnimationTimer_Tick; richTextBoxTarget.Clear(); // 此处可追加加载完成后需要显示的实际业务内容 }
适配提示:如果RichTextBox需要同时展示其他内容,不需要调用Clear方法,只需记录加载文本的插入起始位置,更新时将SelectionStart设为该位置、选中对应长度的圆点内容替换即可,不会影响控件内其他已存在的文本。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

