Form Random BackColor

If you want to display a random BackColor for your form or simply generate a random color you can use the FromArgb method from the Color class with 3 int random arguments for Red, Green and Blue.

Here is an example where the form's BackColor is changed every time a button is clicked. In this example I've also added 3 labels to display the 3 generated numbers.

private void button1_Click(object sender, EventArgs e)
        {
            Random RandomClass = new Random();

            int rndRed = RandomClass.Next(0, 255);
            int rndGreen = RandomClass.Next(0, 255);
            int rndBlue = RandomClass.Next(0, 255);

            this.BackColor = Color.FromArgb(rndRed, rndGreen, rndBlue);

            lblBlue.Text = "Blue: " + rndBlue.ToString();
            lblGreen.Text = "Green: " + rndGreen.ToString();
            lblRed.Text = "Red: " + rndRed.ToString();
        }

No comments:

Post a Comment