ykh
ykh

Reputation: 1815

How to animate a PictureBox in a Win Forms application?

I have a windows form application with a PictureBox control containing an image. I want to move the PictureBox control to the right in a slow movement. Here is my code:

        Point currentPoint = pictureBox_Logo.Location; 
        for (int i = 0; i < 25; i++)
        {
            pictureBox_Logo.Location = new Point(pictureBox_Logo.Location.X + 1, pictureBox_Logo.Location.Y);
            Thread.Sleep(30);
        }

The problem here is that when the code executes instead of seeing the picture move, I see a white picture move and the moving stops until the picture appears.

What am I missing and what can I do about it?

Upvotes: 1

Views: 8944

Answers (3)

ykh
ykh

Reputation: 1815

My code is good written, but what I did wrong was putting the code in an event:

private void Form1_Shown(object sender, EventArgs e);

But when I put my code in a button it works without any problems.

Upvotes: 0

opewix
opewix

Reputation: 5083

Code:

public partial class Form1 : Form
{
    void timer_Tick(object sender, EventArgs e)
    {
        int x = pictureBox1.Location.X;
        int y = pictureBox1.Location.Y;

    pictureBox1.Location = new Point(x+25, y);

    if (x > this.Width)
        timer1.Stop();
}

public Form1()
{
    InitializeComponent();

    timer1.Interval = 10;
    timer1.Tick += new EventHandler(timer_Tick);
}

private void button1_Click(object sender, EventArgs e)
{
    pictureBox1.Show();
    timer1.Start();
 }

}

original thread is here Move images in C#

Upvotes: 1

Rusty Shackelford
Rusty Shackelford

Reputation: 63

Try to use pictureBox_Logo.Refresh() after Thread.Sleep(30); Or look for standard Timer control.

Upvotes: 0

Related Questions