Read Registry values (to get the desktop icon size) in C#


To make using Registry methods easier, this example defines a RegistryTools class that contains static methods for interacting with the Registry. The following code shows the GetRegistryValue method.

// Get a registry value.
public static object GetRegistryValue(RegistryKey hive,
    string subkey_name, string value_name, object default_value)
    RegistryKey subkey = hive.OpenSubKey(subkey_name, false);
    object result = subkey.GetValue(value_name, default_value);
    return result;

The hive parameter indicates the part of the Registry to search. This should be something like Registry.ClassesRoot, Registry.CurrentConfig, Registry.CurrentUser, Registry.DynData, Registry.LocalMachine, or Registry.PerformanceData.

The method creates a RegistryKey object to work with a subkey inside the hive. The second parameter to OpenSubKey indicates that the method does not need write access to the subkey.

The method then uses the subkey’s GetValue method to get the desired value and returns it. Notice that the return value is a non-specific object. Different registry settings hold different data types, so the calling code is responsible for converting the object into the appropriate data type.

The example program uses the following code to display the desktop icon size.

// Get the desktop icon size.
private void btnGetSize_Click(object sender, EventArgs e)
    object size_string = RegistryTools.GetRegistryValue(
        @"Control Panel\Desktop\WindowMetrics",
        "Shell Icon Size", -1);
    txtSize.Text = size_string.ToString();

This code uses the GetRegistryValue method to get the value stored in:

HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics\Shell Icon Size

It uses ToString to convert the non-specific object into a string and then displays it.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in registry, system. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *