Windows Registry API - Examples

This section provides practical examples demonstrating how to interact with the Windows Registry using various programming languages and APIs.

Reading a Registry Value (C++)

This example shows how to read a string value from the registry using the Windows API.


#include <windows.h>
#include <iostream>
#include <string>

int main() {
    HKEY hKey;
    LONG regOpenResult = RegOpenKeyEx(
        HKEY_CURRENT_USER,       // Root key
        L"Software\\MyApp",      // Subkey name
        0,                       // Reserved
        KEY_READ,                // Desired access
        &hKey                    // Receives handle to open key
    );

    if (regOpenResult == ERROR_SUCCESS) {
        DWORD type;
        TCHAR value[256];
        DWORD dataSize = sizeof(value);

        LONG regQueryResult = RegQueryValueEx(
            hKey,
            L"SettingName",      // Value name
            NULL,                // Reserved
            &type,               // Receives type of value
            (LPBYTE)value,       // Buffer for value data
            &dataSize            // Size of buffer in bytes
        );

        if (regQueryResult == ERROR_SUCCESS && type == REG_SZ) {
            std::wcout << L"Value for 'SettingName': " << value << std::endl;
        } else {
            std::wcerr << L"Failed to query value or value is not REG_SZ." << std::endl;
        }
        RegCloseKey(hKey);
    } else {
        std::wcerr << L"Failed to open registry key." << std::endl;
    }

    return 0;
}
            

Writing a Registry Value (C#)

This C# example demonstrates how to write a DWORD value to the registry using the Microsoft.Win32 namespace.


using Microsoft.Win32;
using System;

public class RegistryWriter
{
    public static void Main(string[] args)
    {
        try
        {
            // Open or create the key
            RegistryKey baseKey = Registry.CurrentUser.CreateSubKey("Software\\MyCSharpApp");

            if (baseKey != null)
            {
                // Write a DWORD value
                baseKey.SetValue("MaxConnections", 100, RegistryValueKind.DWord);
                Console.WriteLine("Successfully wrote DWORD value to registry.");

                // Write a String value
                baseKey.SetValue("DatabasePath", @"C:\Program Files\MyApp\Data", RegistryValueKind.String);
                Console.WriteLine("Successfully wrote String value to registry.");

                baseKey.Close(); // Important to close the key
            }
            else
            {
                Console.WriteLine("Failed to create or open registry key.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}
            
Note: Ensure your application has the necessary permissions to write to the specified registry key. For system-wide settings, you might need administrative privileges.

Enumerating Subkeys (PowerShell)

A simple PowerShell script to list all subkeys under a specific registry path.


$registryPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion"

try {
    Get-ChildItem -Path $registryPath -ErrorAction Stop | ForEach-Object {
        Write-Host $_.Name
    }
} catch {
    Write-Error "Error accessing registry path '$registryPath': $($_.Exception.Message)"
}
            

Deleting a Registry Value (Python)

Using Python's winreg module to delete a registry value.


import winreg

try:
    # Open the key (requires write access)
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\MyApp", 0, winreg.KEY_SET_VALUE)

    # Delete the value
    winreg.DeleteValue(key, "TemporarySetting")
    print("Registry value 'TemporarySetting' deleted successfully.")

    winreg.CloseKey(key)

except OSError as e:
    print(f"Error deleting registry value: {e}")
except FileNotFoundError:
    print("Registry key or value not found.")
            

Key Concepts and Best Practices