Get Random Color

cramopy picture cramopy · Mar 22, 2015 · Viewed 76.8k times · Source

Do you know any method to generate a random Color (not a random Color Name!)?

I've already got one, but this one is'nt doing it correctly:

This only returns Green:

Random r = new Random();
BackColor = Color.FromArgb(r.Next(0, 256), r.Next(0, 256), 0);

This only returns Red:

Random r = new Random();
BackColor = Color.FromArgb(r.Next(0, 256), 0, 0);

This only returns Blue:

Random r = new Random();
BackColor = Color.FromArgb(0, 0, r.Next(0, 256));

I want my Code to return one, random Color, not only green/red/blue every time, as the above ones do.

How to solve this?

Any suggestion will be approved with joy!

Answer

Rufus L picture Rufus L · Mar 22, 2015

Here's the answer I started posting before you deleted and then un-deleted your question:

public partial class Form1 : Form
{
    private Random rnd = new Random();

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {  
        Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));

        BackColor = randomColor;
    }
}