Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

To animate GIF while moving, you may start timer on KeyDown() method and at each Tick, call MoveLeft() method. When you want to stop animation, just press another key to stop the timer. In this way, you'll achieve the animation during movement and also when it is still.

private Timer _timer = new Timer();

_timer.Interval = 10; // miliseconds

void Form1_KeyDown(object sender, KeyEventArgs e)
{        
    if (e.KeyCode == Keys.A)
    {
        _timer.Start();
    }
    if (e.KeyCode == "KEY_FOR_STOPPING_ANIMATION")
    {
        _timer.Stop();
    }
}

void timer1_Tick(object sender, EventArgs e)
{
    MoveLeft();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top