[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use the predefined system colors in C#


The static System.Drawing.SystemColors class defines properties that give the system colors. These include colors for such items as active objects, highlighted text, captions, and window frames.

This example uses the following code to list the defined system colors.

// List the system colors. private void Form1_Paint(object sender, PaintEventArgs e) { int y = 10; // Enumerate the SystemColors class's static Color properties. Type type = typeof(SystemColors); foreach (PropertyInfo field_info in type.GetProperties()) { DrawColorSample(e.Graphics, ref y, (Color)field_info.GetValue(null, null), field_info.Name); } // Size to fit. this.ClientSize = new Size(this.ClientSize.Width, y + 10); }

This code gets a Type object representing the SystemColors class. It calls the object's GetProperties method and loops through the returned property information. For each property, it calls the following DrawColorSample method, passing it the property's color and name.

// Display a color sample. private void DrawColorSample(Graphics gr, ref int y, Color clr, string clr_name) { using (SolidBrush br = new SolidBrush(clr)) { gr.FillRectangle(br, 10, y, 90, 10); } gr.DrawRectangle(Pens.Black, 10, y, 90, 10); gr.DrawString(clr_name, this.Font, Brushes.Black, 110, y); y += 15; }

This method draws a rectangle filled with the color followed by the color's name. It finished by incrementing the variable y so the next color is drawn below this one.

This example uses reflection so it can list all of the system colors, but in a real program you would probably just use a system color as if it were any other color value. For example, the following code sets a form's background to the HotTrack color.

this.BackColor = SystemColors.HotTrack;

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.