我正在使用C#WinForms应用程序,该应用程序使用System.Timers.Timer在for循环中重复之间暂停线程。它是一个幻灯片应用程序,它使用Transitions.dll将图像带到屏幕上。
这里是计时器的全局声明:
public System.Timers.Timer tmrPause = new System.Timers.Timer();
这里是for循环:
private void SlideShow()
{
for (int i = 0; i < lstChosenTBImages.Count; i++)
{
if (i == glbintChosenTBIndex)
glbblIsCorrectImage = true;
if (i == 1 || i == 11)
TransFromLeft(i);
else if (i == 2 || i == 12)
TransFromRight(i);
else if (i == 0 || i == 3)
TransFromTop(i);
else if (i == 4)
TransFromBottom(i);
else if (i == 5 || i == 10)
TransFromBack(i);
else if (i == 6)
TransFromUpperLeft(i);
else if (i == 7)
TransFromUpperRight(i);
else if (i == 8)
TransFromLowerLeft(i);
else if (i == 9)
TransFromLowerRight(i);
}
}
这里是TransFromLeft方法(上面for循环中列出的所有其他转换方法都是相同的):
private void TransFromLeft(int intImage)
{
Point ptPicBoxLoc = glbptpbImageLoc;
PictureBox pbTBImage = new PictureBox();
pbTBImage.Parent = this;
pbTBImage.Size = new Size(196, 200);
pbTBImage.BackColor = Color.Black;
pbTBImage.SizeMode = PictureBoxSizeMode.StretchImage;
pbTBImage.Image = lstChosenTBImages[intImage].imgTBImage;
Transition tFromLeft = new Transition(new TransitionType_Acceleration(750));
pbTBImage.Location = new Point(-1200, pbTBImage.Location.Y);
tFromLeft.add(pbTBImage, "Left", ptPicBoxLoc.X);
tFromLeft.add(pbTBImage, "Top", ptPicBoxLoc.Y);
pbTBImage.Visible = true;
pbTBImage.Refresh();
tFromLeft.TransitionCompletedEvent += tFromLeft_TransitionCompletedEvent;
tFromLeft.run();
}
这是TransFromLeft方法的转换完成事件处理程序:
private void tFromLeft_TransitionCompletedEvent(object sender, Transitions.Transition.Args e)
{
StartTheTimer();
}
这是StartTheTimer方法:
private void StartTheTimer()
{
tmrPause.Enabled = true;
tmrPause.Interval = 2000;
tmrPause.Elapsed += tmrPause_Elapsed;
tmrPause.Start();
}
这里是tmrPaused_Elapsed事件处理程序:
private void tmrPause_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
{
if (this.InvokeRequired == true)
{
Del d = new Del(Prep4NextImage);
}
else
Prep4NextImage();
}
}
最后,Prep4NextImage方法:
private void Prep4NextImage()
{
tmrPause.Stop();
glbblIsCorrectImage = false;
foreach (Control ctrl in this.Controls)
{
if (ctrl is PictureBox)
ctrl.Dispose();
}
}
所有上述方法/事件处理程序都按照上面列出的顺序执行。
应该发生的是,12个图像中的每一个应该逐个出现在屏幕上,图像之间有2秒的暂停。相反,发生了所有12个图像同时出现在屏幕上的情况。 tmrPause无法在图像之间运行所需的2秒,或者某些代码写错了或放错位置。