2015-08-26 95 views

回答

0

呃,這樣的事?

private static Random s_Gen = new Random(); 
... 

// Controls couldn't be (semi-)transparent, so alpha must be 255 
textBox1.BackColor = Color.FromArgb(255, Color.FromArgb(s_Gen.Next())); 
1

使用Random-class。您可以從System.Drawing.KnownColor-enum獲得所有已知的顏色:

KnownColor[] colors = (KnownColor[])Enum.GetValues(typeof(System.Drawing.KnownColor)); 
colors = Array.FindAll(colors, c => c =! KnownColor.Transparent); // is not allowed 
Random r = new Random(); 
KnownColor randomColor = colors[r.Next(colors.Length)]; 
textbox1.BackColor = Color.FromKnownColor(randomColor); 

注意,你不應該調用一個循環這個代碼,否則它將始終產生相同的「隨機」數字,因爲它是與當前的時間播種。而是重新使用相同的隨機實例。因此,如果它在循環中,則聲明並初始化循環外部的隨機變量。