我在 3 个不同的图片框中随机显示图像,并使用计时器控制以某个固定的时间间隔更改它们。
当我关闭应用程序并再次打开它时,我会随机显示图像,但我希望图像使用计时器随机显示,但我不明白为什么计时器不工作!我在哪里做错了?
Random random = new Random();
List<string> filesToShow = new List<string>();
List<PictureBox> pictureBoxes;
public Form2()
{
InitializeComponent();
Timer timer2 = new Timer();
pictureBoxes = new List<PictureBox> {
pictureBox3,
pictureBox4,
pictureBox5
};
//ShowRandomImages();
// Setup timer
timer2.Interval = 1000; //1000ms = 1sec
timer2.Tick += new EventHandler(timer2_Tick);
timer2.Start();
}
private void ShowRandomImages()
{
foreach (var pictureBox in pictureBoxes)
{
if (!filesToShow.Any())
filesToShow = GetFilesToShow();
int index = random.Next(0, filesToShow.Count);
string fileToShow = filesToShow[index];
pictureBox.ImageLocation = fileToShow;
filesToShow.RemoveAt(index);
}
}
private List<string> GetFilesToShow()
{
string path = @"C:\Users\Monika\Documents\Visual Studio 2010\Projects\StudentModule\StudentModule\Image";
return Directory.GetFiles(path, "*.jpg", SearchOption.TopDirectoryOnly).ToList();
}
private void timer2_Tick(object sender, EventArgs e)
{
if (sender == timer2)
{
//Do something cool here
ShowRandomImages();
}
}