問題是UI線程沒有機會更新顯示。那就是:圖片顯示爲,但UI不更新。
一個不那麼好的,黑客是使用Application.DoEvents
讓這樣的UI更新本身:
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);
}
因此,按當另一個(更清潔)的解決辦法是改變你的邏輯按鈕啓動一個定時器,用於更改圖片,每5秒運行一次。我假設你正在使用Windows窗體,所以你可以把一個表單上名爲timer
Timer
,附加一個事件處理程序Elapsed
事件,然後使用此:
// 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();
}
}
內計時器事件,使用此代碼:
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();
}
}
我很困惑這裏的消息框的用途是什麼,但是'Thread.Sleep'不會是正確的解決方案。 –
消息框可能只是一個調試解決方案,以查看循環是否運行。當然,在關閉該框之後,UI將被刷新,而沒有消息框的情況並非如此。 –
消息框不是我需要的東西,它只是用於測試 – marios