我正在使用此代码使用计时器一次在 3 个图片框中随机显示图像,现在我在我的文件夹中使用 5 个图像对其进行测试,最初它在 3 个图片框中正确显示不同的图像,但后来出现相同的图像2个图片框甚至3个图片框显示相同的图像,如何避免在多个图片框中同时显示相同的图像
public partial class Form2 : Form
{
Random random = new Random();
List<String> filesToShow = new List<string>();
List<PictureBox> pictureBoxes;
string LoginName;
public Form2(string userName)
{
InitializeComponent();
this.LoginName = userName;
label1.Text = "Welcome " + userName;
timer2 = new Timer();
pictureBoxes = new List<PictureBox> {
pictureBox3,
pictureBox4,
pictureBox5
};
// Setup timer
timer2.Interval = 5 * 1000; //1000ms = 1sec
timer2.Tick += new EventHandler(timer2_Tick);
timer2.Start();
panelHide = panel4;
}
public static Panel panelHide = new Panel();
private void ShowRandomImages()
{
foreach (var pictureBox in pictureBoxes)
{
if (filesToShow != null && !filesToShow.Any())
{
filesToShow = GetFilesToShow();
}
if (filesToShow != null && filesToShow.Any()) // If any files then allow the code to delete the shown images
{
int index = random.Next(0, filesToShow.Count);
string fileToShow = filesToShow[index];
pictureBox.ImageLocation = filesToShow[index];
filesToShow.RemoveAt(index);
}
}
}
private List<String> GetFilesToShow()
{
String str = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string path = str + "\\Image\\";
return Directory.GetFiles(path, "*.jpg", SearchOption.TopDirectoryOnly).ToList();
}
private void timer2_Tick(object sender, EventArgs e)
{
if (sender == timer2)
{
ShowRandomImages();
}
}
}
在此先感谢您的帮助