Thursday, July 12, 2012

How to generate random color in C#?

In some of the case, we have a requirement to generate Random color for controls, this can be done by using Random class, Random class allows us to generate random number from given range, as we know that we can generate color using number combination, like (256,256,256).

Color is generated using combination of (256,256,256) numbers, these numbers represent RGB colors means RED, GREEN, BLUE colors. Every color is combination of RED, GREEN, BLUE colors only. So to generate random color we have to generate random combination of these numbers (256,256,256).

 Here I am explaining - How to generate random color in C#?
In this example, I have used Color.FromArgb() method, which accepts these parameters for color combination. This method returns generated color using given parameters, but we have to generate random color so we have to pass random color combination.

Here is code-

   private void button1_Click(object sender, EventArgs e)
            //Generating object for Random class 
            Random objRand = new Random();
            //Generating object for Color class
             Color objColor = Color.FromArgb(objRand .Next(256),objRand .Next(256),objRand .Next(256));

            //Assigning newly generated color to Button1 

            button1.ForeColor = objColor ; 

In this code, first I have defined object of Random class, which will help us to generate random number.  After that using Color class object I am generating color combination-

   Color objColor = Color.FromArgb(objRand .Next(256),objRand .Next(256),objRand .Next(256));

This line of code will return color which will be in format of color call object so we need any color class object to hold this color. Here I have declared one object by named objColor which is representing color class object. 

Finally I am assigning generated color to Button1.

   button1.ForeColor = objColor ;

Here objColor is object of color class which holds generated random color using  Color.FromArgb() function.


No comments:

Post a Comment