[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: Read Registry values (to get the desktop icon size) in C#

[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); subkey.Close(); 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( Registry.CurrentUser, @"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 the example to experiment with it and to see additional details.

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