I have a program that will move a gif inside a picturebox in a random direction, but when the function is called then the gif will freeze. However, when I move the box using a keyDown function to move the picture box, it remains animate. How can I make it remain animated while it is moving?
This is what I used to make it move for a random distance, which freezes the gif.
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
eventDuration = randomizer.Next(30, 70);
while (eventDuration != 0)
{
MoveLeft();
eventDuration = eventDuration - 1;
Thread.Sleep(15);
}
}
}
private void MoveLeft()
{
_y = picPicture.Location.Y;
_x = picPicture.Location.X;
picPicture.Location = new System.Drawing.Point(_x - 1, _y);
}
However, if use this, it moves smoothly without freezing the gif, even when I'm holding down the A key. I can't use this method because it requires constant user input, while the first was autonomous in the direction it moved
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
MoveLeft();
}
}
private void MoveLeft()
{
_y = picPicture.Location.Y;
_x = picPicture.Location.X;
picPicture.Location = new System.Drawing.Point(_x - 1, _y);
}
How can I move my picture box for a random distance without pausing the gif?
If you use Thread.Sleep
, your application does not process any window events, including redrawing. The proper way to do this is to use Timer
class. When A key is pressed, you should enable the timer and move controls in its Tick
event.
Alternatively, you can call Application.DoEvents
method after Thread.Sleep
, but it's a bad practice.