您可以尝试创建一个新List<string>
文件,其中列出了所有具有您选择的特定扩展名的文件。Random
然后,考虑到范围不会超过我们的值,初始化一个新类,该类在特定范围内获取随机数List<string>.Count
。
例子
假设CurrentClicks
标识一个新整数并且MaximumClicks
是我们的最大值
public Form1()
{
InitializeComponent();
button1.Click += new EventHandler(button1_Click); //Link the Click event of button1 to button1_Click
}
const int MaximumClicks = 5; //Initialize a new constant int of value 5 named MaximumClicks
int CurrentClicks = 0; //Initialize a new variable of name CurrentClicks as an int of value 0
以下可能适用
private void button1_Click(object sender, EventArgs e)
{
if (CurrentClicks < MaximumClicks) //Continue if CurrentClicks is less than 5
{
string FilesPath = @"D:\Resources\International"; //Replace this with the targeted folder
string FileExtensions = "*.png"; //Applies only to .png file extensions. Replace this with your desired file extension (jpg/bmp/gif/etc)
List<string> ItemsInFolder = new List<string>(); //Initialize a new Generic Collection of name ItemsInFolder as a new List<string>
foreach (string ImageLocation in Directory.GetFiles(FilesPath, FileExtensions)) //Get all files in FilesPath creating a new string of name ImageLocation considering that FilesPath returns a directory matching FileExtensions considering that FileExtensions returns a valid file extension within the targeted folder
{
ItemsInFolder.Add(ImageLocation); //Add ImageLocation to ItemsInFolder
}
Random Rnd = new Random(); //Initialize a new Random class of name Rnd
int ImageIndex = Rnd.Next(0, ItemsInFolder.Count); //Initialize a new variable of name ImageIndex as a random number from 0 to the items retrieved count
pictureBox1.Load(ItemsInFolder[ImageIndex]); //Load the random image based on ImageIndex as ImageIndex belongs to a random index in ItemsInFolder
CurrentClicks++; //Increment CurrentClicks by 1
}
else
{
//Do Something (MaximumClicks reached)
}
}
这将在提供的文件夹中获取与指定扩展名匹配的文件位置。PictureBox
然后,从收集到name的文件位置加载一个随机文件pictureBox1
。
但是,这不会避免之前添加到PictureBox
. 如果您想避免重复,您可以创建一个新int
数组或List<int>
添加所有ImageIndex
应用到的数组,PictureBox
但建议使用它,List<int>
因为它似乎更易于管理
例子
List<int> AlreadyAdded = new List<int>();
redo:
Random Rnd = new Random();
int ImageIndex = Rnd.Next(0, ItemsInFolder.Count);
if (AlreadyAdded.Contains(ImageIndex)) //Continue within this block if the item already exists in AlreadyAdded
{
goto redo;
}
AlreadyAdded.Add(ImageIndex); //Add ImageIndex to AlreadyAdded
谢谢,
我希望你觉得这有帮助:)