Créer une animation avec un ‘thread’

Author:

Modifier,le,mode,de,composition,d'une,image
{filelink=16665}

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

public class AnimerCercle : Form {
  private int x = 10, y = 10;
  private int width = 200, height = 200;

  private Button suspendre = new Button();
  private Button reprendre= new Button();
  private Button arrêter = new Button();
  private Thread thread;

  public AnimerCercle() {
      Text = "Exemple de thread et Animation";
    BackColor = Color.White;
    arrêter.Text = "Arrêter";
    suspendre.Text = "Suspendre";
    reprendre.Text = "Reprendre";

    Controls.Add(suspendre);
    Controls.Add(reprendre);
    Controls.Add(arrêter);

    int w = 20;
    suspendre.Location = new Point(w, 5);
    reprendre.Location = new Point(w += 10 + suspendre.Width, 5);
    arrêter.Location = new Point(w += 10 + reprendre.Width, 5);

    arrêter.Click += new EventHandler(Arrêter_Click);
    suspendre.Click += new EventHandler(Suspendre_Click);
    reprendre.Click += new EventHandler(Reprendre_Click);
    reprendre.Enabled = false;
    thread = new Thread(new ThreadStart(Run));
    thread.Start(); // lancer l'animation
  }
  protected void Arrêter_Click(object sender, EventArgs e) {
    thread.Abort(); // Arrêter l'animation
    reprendre.Enabled = false;
    suspendre.Enabled = false;
  }
  protected void Suspendre_Click(object sender, EventArgs e) {
    thread.Suspend(); // Suspendre l'animation
    reprendre.Enabled = true;
  }
  protected void Reprendre_Click(object sender, EventArgs e) {
    thread.Resume(); // Repredndre  l'animation
    reprendre.Enabled = false;
  }
  protected override void OnPaint( PaintEventArgs e )   {
    Graphics g = e.Graphics;
    Pen green = new Pen(Color.Green, 3);
    Brush red = new SolidBrush(Color.Red);
    g.DrawEllipse(green, x, y, width, height);
    base.OnPaint(e);
  }
  public void Run()
  {
    int dx=9, dy=9;
    while (true) {
      for (int i = 0; i < 30; i++) {
        x += dx;
        y += dy;
        width -= dx;
        height -= dy;
        Invalidate();
        Thread.Sleep(30);
      }
      dx = -dx; dy = -dy;
    }
  }
  public static void Main( ) {
    Application.Run(new AnimerCercle());
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *