C# Slideshow only displays last image after time is up for all slides/picturebox not becoming visible

StackOverflow https://stackoverflow.com/questions/10384433

Domanda

I am currently trying to create a program that will show a slideshow of pictures from an ImageList with variable show times from a ListView, which is acessed through a numericUpDown, but when I click the button to start, nothing happens, until the time of the slideshow ends, where the last slide is shown, then disappears straight away (if i leave out "pictureBox1.Visible = false" at the end, it stays).

current code:

private void buttonSlideshow_Click(object sender, EventArgs e)
{
    pictureBox1.Visible = true;

    for (int s = 0; s < listView1.Items.Count; s++)
    {
        listView1.Items[s].Selected = true;
        pictureBox1.Image = imageList1.Images[s];

        DateTime later = DateTime.Now.AddMilliseconds((double)numericUpDown1);
        while (DateTime.Now < later)
        {
        }

    }
        pictureBox1.Visible = false;
}

I have tried many versions of this (including using timers and switching code around) have no idea what is going wrong

numericUpDown1 is the duration of the slide, have been using integers for testing, still doesn't work

È stato utile?

Soluzione

Doing this:

while (DateTime.Now < later)

Is blocking your UI thread. It can't redraw the screen while you are keeping it busy spinning it's wheels. Use a timer with a call back instead.

You'll need to rework your code slightly. Rather than use a for loop, define a variable for your current slide, initialize it to zero in your click handler, make your picture box visible, load the first picture and then start your timer.

In your timer handler, you'll increment the current index, check it against the length of you list of slides and, if you still have slides to display, load the next one and then start the timer again (or you can use a timer that fires repeatedly, although you might want to be careful that it doesn't fire again before you're done handling that last one). If there are no more slides left, just do you clean up and make your picture box invisible again.

One final note, be careful with which thread the timer is going to fire on. In win forms you can use System.Windows.Forms.Timer which fires on the UI thread and you won't have any problems. In WPF you can use DispatcherTimer which also fires on the UI thread. Other timers generally run in their own thread and you'll have to handle pushing anything that's supposed to update the UI back to the UI thread.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top