Move image (Picturebox) in form

Asked

Viewed 1,026 times

0

How to move an image in a windows form.

I used the following code:

private void button1_Click(object sender, EventArgs e)
{
    int tamanhoFundo = picFundo.Width;
    int x = myPic.Location.X;
    int y = myPic.Location.Y;
    while (x < tamanhoFundo)
    {
        int pos = x += 5;
        myPic.Location = new Point(pos, myPic.Location.Y);
        Thread.Sleep(500);
    }
}

It even moves the image, only there’s a trace:

inserir a descrição da imagem aqui

How to prevent this?

2 answers

2


If the image is above the picFundo, before calling the Thred.Sleep give a Refresh() in the background. Look at the code below:

private void button1_Click(object sender, EventArgs e)
{
    int tamanhoFundo = picFundo.Width;
    int x = myPic.Location.X;
    int y = myPic.Location.Y;
    while (x < tamanhoFundo)
    {
        int pos = x += 5;
        myPic.Location = new Point(pos, myPic.Location.Y);
        picFundo.Refresh();
        Thread.Sleep(500);
    }
}
  • That’s right. Thanks, thank you very much.

1

This occurs in a purposeful form of self System.Windows.Forms, because of increasing the performance of window rendering. But you can disable this with the method Refresh() and Update(), the two are great to render your window. see the example based on your code:

private void button1_Click(object sender, EventArgs e)
{
  int tamanhoFundo = picFundo.Width;
  int x = myPic.Location.X;
  int y = myPic.Location.Y;
  while (x < tamanhoFundo)
  {
     int pos = x += 5;
     myPic.Location = new Point(pos, myPic.Location.Y);
     myPic.Refresh(); myPic.Update();
     Thread.Sleep(250); // Também é bom reduzir o tempo de Sleep, pois os métodos Refresh() e Update() consomem um pouco de memória para re-criar o componente, então, de 500 vamos colocar 250.
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.