How can i move the Rectangle on the form and animate it as it moves?

If i want to move it for example to the right, i must increase it's X cordinate, right? I did it (++x) and drawed a new rectangle and overdrawed the old one with background color. Is it right? or maybe there is better idea?

Is there any timer to slow down the animation process?

Thnx in advance :)

6 Years
Discussion Span
Last Post by ddanbe

The snippet ddanbe has given you uses thread.sleep to slow the draw process down. Another option is the Timer class which has a tick event that fires at a set interval.


Add a timer using the toolbox, then in the timer tick, make it clear the screen and redraw the rectangle.
You can use arrays to store position/size values, and a for loop to go through each item in the array.

You can use Timer.Interval to change the delay, in milliseconds. Timers should be very simple to understand, as they have only a few properties.


When i'm clearing the screen, the moves done before will be also cleared, but i want the rectangle to leave prints after each move.


If you want the previous locations to stay put then you will need to store them.
You could save an image file of the form before you clear it then paint the image back to the form before adding the new rectangle, or you could store each location the rectangle goes to in a list and paint each one back to the form in the paint event:

List<Rectangle> locations = new List<Rectangle>();
        private void Form1_Paint(object sender, PaintEventArgs e)
            foreach (Rectangle rect in locations)
                e.Graphics.DrawRectangle(new Pen(Brushes.Black), rect);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.