用c#暂停图像
本文关键字:图像 暂停 | 更新日期: 2023-09-27 18:01:50
我想制作一个程序,每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);
}
}
问题是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();
}
}
做到这一点的最好方法是与计时器控件结合使用。将计时器的间隔设置为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();
}
}