Use RegKey for Registry Operations
masterThe RegKey class is the primary interface for interacting with the Windows Registry. It wraps raw HKEY handles and provides methods for opening keys and retrieving values.
Error Handling Patterns
WinReg provides three ways to handle errors:
- Exceptions: Standard methods (e.g.,
Open,GetDwordValue) throw aRegExceptionon failure. - Return Codes:
Trymethods (e.g.,TryOpen) return aRegResultobject which can be checked for success. - Expected Values:
TryGet...Valuemethods return aRegExpected<T>object, which contains either the value or aRegResulton error.
// 1. Exception-based usage
RegKey key{ HKEY_CURRENT_USER, L"SOFTWARE\SomeKey" };
DWORD dw = key.GetDwordValue(L"SomeDwordValue");
// 2. Return-code based usage (TryOpen)
RegKey key;
RegResult result = key.TryOpen(HKEY_CURRENT_USER, L"SOFTWARE\SomeKey");
if (!result) {
// Handle error using result.Code or result.ErrorMessage
}
// 3. RegExpected based usage (TryGetDwordValue)
const auto res = key.TryGetDwordValue(L"SomeDwordValue");
if (res.IsValid()) {
DWORD val = res.GetValue();
} else {
// Handle error using res.GetError()
}