The problem is that the UI thread has no chance to update the display. That is: The images are being shown, but the UI does not update.
A not-so-nice-hack would be to use Application.DoEvents
to let the UI update itself like this:
for (int i = 0; i < 6; i++)
{
button1.BackgroundImage = (Image)Properties.Resources.ResourceManager.GetObject(arr1[i]);
Application.DoEvents();
new SoundPlayer(Properties.Resources.nero).Play();
Thread.Sleep(5000);
}
Another (much cleaner) solution would be to change your logic so that when pressing the button a timer is started that changes the pictures, running every 5 seconds. I'm assuming you're using Windows Forms, so you can place a Timer
named timer
on your form, attach an event handler to the Elapsed
event and then use this:
// These are instance members outside any methods!!
private int currentImageIndex = 0;
string[] arr1 = new string[] { "water", "eat", "bath", "tv", "park", "sleep" };
private void button1_Click(object sender, EventArgs e)
{
// EDIT: As per comments changed to turn the button into a Start/Stop button.
// When the button is pressed and the timer is stopped, the timer is started,
// otherwise it is started.
// Stop the timer if it runs already
if (timer.Enabled)
{
timer.Stop();
}
// Start the timer if it was stopped
else
{
// Make the timer start right away
currentImageIndex = 0;
timer.Interval = 1;
// Start the timer
timer.Start();
}
}
Within the timer event, use this code:
private void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
try
{
timer.Interval = 5000; // Next time, wait 5 secs
// Set the image and select next picture
button1.BackgroundImage = (Image)Properties.Resources.ResourceManager.GetObject(arr1[currentImageIndex]);
currentImageIndex++;
}
finally
{
// Only start the timer if we have more images to show!
if (currentImageIndex < arr1.Length)
timer.Start();
}
}