Random Color from Known Color List
Some one in an asp.net forum asked how to select a random color from the list of known colors so I wrote a little code to do this. I wrote a GetRandomColor and GetRandomNumber method which uses the RandomNumberGenerator from the System.Security.Cryptography namespace. As far as I know this is the best random number generator built into the .Net Framework.
using System.Drawing; using System.Security.Cryptography;
...
public static Color GetRandomColor() { KnownColor[] colors = (KnownColor[])Enum.GetValues(typeof(KnownColor)); return Color.FromKnownColor(colors[GetRandomNumber(colors.Length)]); }
public static int GetRandomNumber(int maxValue) { RandomNumberGenerator rng = RNGCryptoServiceProvider.Create();
byte[] bytes = new byte[4];
rng.GetBytes(bytes);
int ranNum = BitConverter.ToInt32(bytes, 0);
return Math.Abs(ranNum % maxValue); }