C#实现跑马灯效果的示例代码

  public partial class CustomLable : Label

  {

  System.Timers.Timer timer = new System.Timers.Timer(200);

  int offset = 5;//偏移量

  PointF textPoint;

  public CustomLable()

  {

  InitializeComponent();

  textPoint = new PointF(this.Width, 0);

  timer.Elapsed += (s, e) =>

  {

  try

  {

  if (!IsDisposed)

  {

  Graphics g = CreateGraphics();

  SizeF textSize = g.MeasureString(Text, Font);

  textPoint.X -= offset;

  if (textPoint.X <= -textSize.Width)

  {

  textPoint.X = Width;

  }

  g.Clear(BackColor);

  g.DrawString(Text,Font, new SolidBrush(ForeColor), textPoint);

  }

  }

  catch { }

  };

  }

  protected override void OnPaint(PaintEventArgs pe)

  {

  base.OnPaint(pe);

  }

  private bool _IsMarquee;

  [Browsable(true)]

  [Description("是否以跑马灯效果显示")]

  public bool IsMarquee

  {

  get { return _IsMarquee; }

  set

  {

  _IsMarquee = value;

  Marquee();

  }

  }

  public void Marquee()

  {

  if (IsMarquee)

  {

  timer.Start();

  }

  else

  {

  timer.Stop();

  textPoint = new PointF(0, 0);

  try

  {

  if (!IsDisposed)

  {

  Graphics g = CreateGraphics();

  g.Clear(BackColor);

  g.DrawString(Text, Font, new SolidBrush(ForeColor), textPoint);

  }

  }

  }

  }

  }