我想制作一个每5秒显示一个图像的程序,然后暂停1秒然后显示下一个。但是我有一个问题暂停图像。如果我有消息框代码,它会停止显示图像我必须按确定继续,但如果没有显示图像,它会跳转到最后一张图像。请帮助,我必须在我的代码中添加什么才能正常工作?
private void button1_Click(object sender, EventArgs e)
{
string[] arr1 =
new string[] { "water", "eat", "bath", "tv", "park", "sleep" };
for (int i = 0; i < 6; i++)
{
button1.BackgroundImage =
(Image)Properties.Resources.ResourceManager.GetObject(arr1[i]);
new SoundPlayer(Properties.Resources.nero).Play();
MessageBox.Show(arr1[i].ToString());
Thread.Sleep(5000);
}
}
答案 0 :(得分:2)
问题是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
的{{1}},将事件处理程序附加到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();
}
}
答案 1 :(得分:0)
最好的方法是与定时器控制一起使用。将计时器的间隔设置为1秒,但最初将其禁用。然后按下按钮代码只需启用计时器。
public partial class MyForm : Form
{
private int ImagePosition = 0;
private string[] arr1 = new string[] { "water", "eat", "bath", "tv", "park", "sleep" };
private void button1_Click(object sender, EventArgs e)
{
ImagePosition = 0;
RotateImage();
Timer1.Start();
}
private void RotateImage()
{
button1.BackgroundImage =
(Image)Properties.Resources.ResourceManager.GetObject(arr1[ImagePosition]);
new SoundPlayer(Properties.Resources.nero).Play();
ImagePosition++;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (ImagePosition > 5)
{
timer1.Enabled = false;
return;
}
RotateImage();
}
}