Search code examples
c#.netwinformspicturebox

pictureBox works fine step by step, but when executed, it seems to execute the timer tick twice each time


I'm making a simple screensaver that shows a set of pictures without repeating them before showing them all. The thing is, the pictureBox is skipping some updates or something, or changing between two pictures really fast. Other times it stays on the same image for too long.

It works just fine in debug mode, even when I hit continue several times, except when i hit continue too fast.

The picturebox updates are tied to a timer which fires once each 2 seconds.

private void timer1_Tick(object sender, EventArgs e)
    {
        if (pictureBox1.Image != null) { pictureBox1.Image.Dispose();}
        pictureBox1.Image = (Image)siguienteImagenAMostrar.Clone(); 
        //siguienteImagenAMostrar is an Image, and it´s the one i want to show next 
        pictureBox1.Invalidate();
        pictureBox1.Update();
        if (siguienteImagenAMostrar != null) { siguienteImagenAMostrar.Dispose(); }
        siguienteImagenAMostrar = siguienteImagen(); //I try to preload the Image         
    }

Here is the siguienteImagen() code, just in case it has something to do with the Random I used:

private Image siguienteImagen()
        {
            int imagenAmostrar;
            do
            {
                imagenAmostrar = rand.Next(0, files.Length);
            } while (currentImage == imagenAmostrar && files.Length > 1);

            int original = imagenAmostrar;

            if (mostrada[imagenAmostrar]) {
                imagenAmostrar = (imagenAmostrar + 1) % files.Length;
                while (mostrada[imagenAmostrar] && original != imagenAmostrar)
                {
                    imagenAmostrar = (imagenAmostrar + 1) % files.Length;
                }
                if (imagenAmostrar == original) 
                {
                    mostrada = Enumerable.Repeat(false, files.Length).ToArray();
                }
            }
            mostrada[imagenAmostrar] = true;
            currentImage = imagenAmostrar;
            string imagenMostrarString = files[imagenAmostrar];
            return Image.FromFile(imagenMostrarString);

        }

Edit: This function seems not to be the problem as simply choosing the next image as currentImage = (currentImage + 1) % files.Length still has the issue of not showing the pictures properly.

Also mostrada is an array of bool which knows if that picture was already shown. files is an array with the path to the pictures. The same index represents the same image on both.


Solution

  • The thing that happened was that i had timer1.Tick += new EventHandler(timer1_Tick); in the form_load() function. I'm still not sure why it worked in step by step mode

    Removing the apparently extra EventHandler i had, solved my problem.