Start New Discussion within our Software Development Community

You can make any color you like by setting the r, g and b values of a Color structure. But .NET has a set of predefined colors that you can use by name, so that you can simply set the backgroundcolor of a form with Color.LawnGreen for instance. Ever wondered what all those color names are? MSDN has some code example that prints all those names in their respective color. Ever tried to read the string “GhostWhite” in the color GhostWhite on a White background? So I made this snippet, which prints all the colornames in black together with a little circle in the respective color.
Create a new Forms application and call ShowKnownColors from the Paint event handler of the Form because you also need a Graphics object from PaintEventArgs.

private void ShowKnownColors(Graphics Grf)
        {
            this.Size = new Size(1150, 680);//make size of Form big enough

            // Get all the values from the KnownColor enumeration.
            System.Array colorsArray = Enum.GetValues(typeof(KnownColor));
            KnownColor[] allColors = new KnownColor[colorsArray.Length];

            Array.Copy(colorsArray, allColors, colorsArray.Length);

            // Loop through printing out the values' names in the colors 
            // they represent.
            float y = 0;
            float x = 20.0F;

            for (int i = 0; i < allColors.Length; i++)
            {
                // If x is a multiple of 20, start a new column.
                if (i > 0 && i % 20 == 0)
                {
                    x += 120.0F;
                    y = 30.0F;
                }
                else
                {
                    y += 30.0F; // Otherwise, increment y by 30.
                }
                string ColorStr = allColors[i].ToString();
                PrintColorAndString(x, y, Color.FromName(ColorStr), ColorStr, Grf);
            }
        }

        private void PrintColorAndString(float x, float y, Color C, string S, Graphics G)
        {
            //draw a color in a circle, together with it's name
            const float D = 18.0F; //diameter of circle
            const float Off = 3.0F;

            Pen BlackPen = new Pen(Color.Black);
            Pen ColorPen = new Pen(C);
            G.DrawEllipse(BlackPen, x, y, D, D);        //draw a black perimeter
            G.FillEllipse(ColorPen.Brush, x, y, D, D);  //fill the inside with the color
            G.DrawString(S, this.Font, BlackPen.Brush, x + D + Off, y + Off);
        }
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.