25
Lesson 25 of 35 ยท WinForms

Timers & Animation

The Timer control lets you execute code at regular intervals. Combined with GDI+ repainting, it enables smooth animations inside WinForms applications.

Using the Timer Control

Drag a Timer from the Toolbox. Set Interval (milliseconds) and Enabled = true, or call Start(). Double-click to generate the Tick event handler.

Timer tick TimerDemo.cs
private int _seconds = 0;

private void timer1_Tick(object sender, EventArgs e)
{
    _seconds++;
    lblTimer.Text = TimeSpan.FromSeconds(_seconds).ToString(@"mm\:ss");
}

Animating a Moving Ball

Keep track of position and velocity. On each Tick, update position and bounce off the edges. Call panel1.Invalidate() to trigger a repaint.

Ball animation BallAnim.cs
private float _x = 50, _y = 50;
private float _vx = 3, _vy = 2;
private const int R = 25;

private void timer1_Tick(object sender, EventArgs e)
{
    _x += _vx;
    _y += _vy;
    if (_x < R || _x > panel1.Width  - R) _vx = -_vx;
    if (_y < R || _y > panel1.Height - R) _vy = -_vy;
    panel1.Invalidate();
}

private void panel1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    e.Graphics.FillEllipse(Brushes.DodgerBlue,
        _x - R, _y - R, R * 2, R * 2);
}