您可以嘗試創建一個新的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)
}
}
這將讓內的文件位置提供與指定擴展名匹配的文件夾然後,從收集的文件位置中加載一個隨機文件,名稱爲pictureBox1
的PictureBox
。
但是,這將不會避免以前添加到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
謝謝,
我希望對您有所幫助:)
根據你正在做的或者有..do要加載2個圖像什麼的5倍磨片用戶點擊一次按鈕..?如果是這樣,那麼這種方法是不正確的..如果我正確理解你的問題,你將需要5個圖片框..或者你需要創建動態5圖片盒.. – MethodMan
感謝DJ Kraze - 我需要2個圖片框加載每次單擊按鈕時最多可以點擊5次不同的圖像..有意義嗎? –
你是否需要這些圖像是隨機或只是一個硬編碼進展 –