Title: Use reflection to list SystemInformation properties in C#
This example shows how you can use reflection to get the properties defined by the SystemInformation class.
The SystemInformation class is chock-full of useful properties that give information about system parameters. These include such values as the thickness of a text caret, the size of menu buttons, the default font, and the name of the computer. The example Use reflection to list a class's properties in C# explains how to list a class's properties. This example uses the reflection techniques explained in that post to explore the SystemInformation class and list its properties and their values.
When the program's form loads, the following code displays information about the class's properties.
// List the SystemInformation class's properties.
object property_value;
PropertyInfo[] property_infos =
typeof(SystemInformation).GetProperties(
BindingFlags.FlattenHierarchy |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Static);
foreach (PropertyInfo info in property_infos)
{
string name = info.Name;
string value = "";
// See if it's an array.
if (!info.PropertyType.IsArray)
{
// It's not an array.
if (info.CanRead) property_value =
info.GetValue(this, null);
else property_value = "---";
if (property_value == null)
value = "<null>";
else
value = property_value.ToString();
}
else
{
// It is an array.
name += "[]";
value = "lt;array>";
}
ListViewMakeRow(lvwProperties, name, value);
}
The code gets the SystemInformation class's type and calls its GetProperties method to get information about the class's properties. See the example Use reflection to list a class's properties in C# for information about the BindingFlags parameters.
The code then loops through the PropertyInfo objects that GetProperties returns. The code gets the properties' names and values, and calls the ListViewMakeRow method to display the information in the form's ListView control. Download the example program to see how the ListViewMakeRow method works and for other details.
Download the example to experiment with it and to see additional details.
|