miércoles, 3 de diciembre de 2014

C# - How to generate a random color (using random color names method)



Hi again!
Another method to generate a random color is by doing the following:
1.- Get the color names of Known Colors in an array.
2.- Get any color of the array by using a random number
3.- Get the color name and display it and apply the color to a control

You can use the code below:


private void button1_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            KnownColor[] names = (KnownColor[])Enum.GetValues(typeof(KnownColor));
            KnownColor rColorName = names[r.Next(names.Length)];
            Color rColor = Color.FromKnownColor(rColorName);
            this.BackColor = rColor;
            button1.Text = rColorName.ToString();
        }

That color can be applied to a control. I applied it to the Form, and looks like this every time I click the “Action!” button:


No hay comentarios.:

Publicar un comentario