Random colors not so random

G

Guest

Hello all, I'm trying to program a random color generator as follows:

Color = Color.FromArgb( (rnd.Next(0,255)), (rnd.Next(0,255)),
(rnd.Next(0,255)) );

When executing, the colors generated from the above line always appear the
same, certainly not random. What is the correct way to generate random
colors?
 
B

Brian P. Hammer

Lionel,

From the help...
Before calling Rnd, use the Randomize statement without an argument to
initialize the random-number generator with a seed based on the system
timer.

HTH,
Brian
 
H

Herfried K. Wagner [MVP]

Brian P. Hammer said:
Before calling Rnd, use the Randomize statement without an argument to
initialize the random-number generator with a seed based on the system
timer.

Mhm... The OP doesn't seem to use VB.NET's 'Rnd' function, thus no call to
'Randomize' is required.
 
B

Brian P. Hammer

Leave it to a newbie to through something out. ;-)

That's why I generally ask more then I contribute.

Brian
 
B

Bob Powell [MVP]

Random rnd=new Random((int)DateTime.Now.Millisecond);

SolidBrush sb=new
SolidBrush(Color.FromArgb(rnd.Next(0,255),rnd.Next(0,255),rnd.Next(0,255)));


--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
J

Jon Skeet [C# MVP]

Bob Powell said:
Random rnd=new Random((int)DateTime.Now.Millisecond);

Why do that? Just use:

Random rnd = new Random();

and it'll be time-based already.

However, the important thing is to reuse that Random object, rather
than creating a new one for each use - otherwise if several uses are
within a very short space of time, you'll create several Random objects
with the same seed, and they'll all give the same results.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top