我随机在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();
}
}
答案 0 :(得分:2)
if (sender == timer2)
... timer2
在该范围内不存在 - 编译时错误应阻止您的成功,除非您在更高级别定义另一个实例具有相同名称,在这种情况下,它不是构造函数中的timer2
- 即不是触发事件的那个 - 您正在进行比较。
快速解决方法是从构造函数中的timer2
实例化中删除类型前缀,如下所示:
timer2 = new Timer();