BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Graphics
.NET 1.1+

.NET Known and System Colours

The Color class can represent over sixteen million colour shades with over two hundred and fifty levels of transparency. Often, however, a simple, named colour or a system colour is desired. These can be obtained using the KnownColor enumeration.

Obtaining a KnownColor from a Color Instance

If you have created a Color value from a KnownColor, be it a named or system colour, you can read the KnownColor value using the Color's ToKnownColor method. However, if the Color was constructed from an ARGB value calling this method returns zero, even if the ARGB value matches that of a known colour perfectly.

The code below creates a Color from the ButtonFace system colour, before obtaining the known colour and outputting the value.

Color c = Color.FromKnownColor(KnownColor.ButtonFace);
KnownColor kc = c.ToKnownColor();
Console.WriteLine(kc);            // ButtonFace

Three properties can be used to determine if a known colour was used when instantiating a Color value. Each returns a Boolean value:

  • IsKnownColor. If true, the Color value is a known colour. The property will return false if the value was created from red, green and blue elements, even if these elements match a known colour.
  • IsSystemColor. This property is set to true for Color values created from one of the system colours that vary according to the user's configuration.
  • IsNamedColor. This property is true when the Color value was generated from a KnownColor or by providing a colour name to the FromName method.
Color c = Color.FromKnownColor(KnownColor.AliceBlue);

Console.WriteLine(c.IsKnownColor);  // true
Console.WriteLine(c.IsNamedColor);  // true
Console.WriteLine(c.IsSystemColor); // false

System Colours

Another manner in which you can obtain system colours is with the SystemColors class. This contains a number of static properties that mirror the system colour values in the KnownColor enumeration. Each property returns a Color. The code below demonstrates this by obtaining the button face colour and outputting the red, green and blue element values.

Color c = SystemColors.ButtonFace;
Console.WriteLine(c.IsKnownColor);  // true
Console.WriteLine(c.IsNamedColor);  // true
Console.WriteLine(c.IsSystemColor); // true
12 March 2012