Hi @Farhoud Alimohammadi , Welcome to Microsoft Q&A,
From your code, it can be seen that this is a custom label control of Winform. There is an obvious error that this.timer.Interval cannot be 0.
This is the optimized code:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace xxx
{
public partial class SlidingLabel : Label
{
private readonly Timer _timer = new Timer();
private int _offset = 0;
private bool _isSliding = false;
private bool _directionRight = false;
public SlidingLabel()
{
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint |
ControlStyles.SupportsTransparentBackColor | ControlStyles.ResizeRedraw |
ControlStyles.UserPaint, true);
AutoSize = false;
Width = 30;
Height = 15;
_timer.Interval = 10;
_timer.Tick += Timer_Tick;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_timer.Dispose();
}
base.Dispose(disposing);
}
protected override void OnBackColorChanged(EventArgs e)
{
Invalidate();
base.OnBackColorChanged(e);
}
protected override void OnForeColorChanged(EventArgs e)
{
Invalidate();
base.OnForeColorChanged(e);
}
protected override void OnPaint(PaintEventArgs e)
{
using (var backgroundBrush = new SolidBrush(BackColor))
{
e.Graphics.FillRectangle(backgroundBrush, ClientRectangle);
}
var textSize = TextRenderer.MeasureText(Text, Font);
int yPosition = (Height / 2) - (textSize.Height / 2);
using (var textBrush = new SolidBrush(ForeColor))
{
e.Graphics.DrawString(Text, Font, textBrush, _offset, yPosition);
}
base.OnPaint(e);
}
protected override void OnResize(EventArgs e)
{
_timer.Enabled = true;
base.OnResize(e);
}
private void Timer_Tick(object sender, EventArgs e)
{
var textSize = TextRenderer.MeasureText(Text, Font);
int maxOffset = textSize.Width - Width;
if (textSize.Width <= Width)
{
_timer.Stop();
_offset = 0;
Invalidate();
}
else
{
if (_offset <= -maxOffset)
{
_directionRight = true;
}
else if (_offset >= 0)
{
_directionRight = false;
}
_offset += _directionRight ? 1 : -1;
Invalidate();
}
}
public int SlideTime
{
get => _timer.Interval;
set
{
_timer.Interval = value;
Invalidate();
}
}
public bool Slide
{
get => _isSliding;
set
{
_isSliding = value;
_timer.Enabled = _isSliding;
if (!_isSliding)
{
_offset = 0;
Invalidate();
}
}
}
public override string Text
{
get => base.Text;
set
{
base.Text = value;
_timer.Start();
}
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.