从 windows 注册表中获取 REG_DWORD 作为 wstring

Getting REG_DWORD from windows registry as a wstring

我正在做一个应该检查注册表值的测试。我的目标是获取 3 windows 个注册表变量。我正在使用来自此 LINK 的修改后的解决方案。问题是,当我尝试获取 REG_DWORD 的值时,它只会打印空括号。当我尝试在 REG_SZ 上使用它时,它工作得很好。现在我使用这个代码:

wstring UpgradeAutocompleteBeCopyFilesUt::ReadRegValue(HKEY root, wstring key, wstring name)
{
    HKEY hKey;
    if (RegOpenKeyEx(root, key.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
        throw "Could not open registry key";

    DWORD type;
    DWORD cbData;
    if (RegQueryValueEx(hKey, name.c_str(), NULL, &type, NULL, &cbData) != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        throw "Could not read registry value";
    }

    if (type != REG_SZ && type != REG_DWORD)
    {
        RegCloseKey(hKey);
        throw "Incorrect registry value type";
    }

    wstring value(cbData / sizeof(wchar_t), L'[=12=]');
    if (RegQueryValueEx(hKey, name.c_str(), NULL, NULL, reinterpret_cast<LPBYTE>(&value[0]), &cbData) != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        throw "Could not read registry value";
    }

    
    RegCloseKey(hKey);
    
    size_t firstNull = value.find_first_of(L'[=12=]');
    
    if (firstNull != string::npos)
        value.resize(firstNull);

    return value;
}

这就是我打印变量的方式:

std::wcout << L"first: " << regfirst << std::endl;
std::wcout << L"second: " << regsecond << std::endl;
std::wcout << L"third: " << regthird << std::endl;

第三个是REG_DWORD。前两个是 REG_SZ.

有什么方法可以从第三个变量中取出 wstring 吗? 我检查了注册表,应该有一个值“1”。

if (type != REG_SZ && type != REG_DWORD) ...

您只需要区别对待 REG_SZREG_DWORD

为了安全起见,还要为空终止符添加一个额外的 +1。

wstring ReadRegValue(HKEY root, wstring key, wstring name)
{
    HKEY hKey;
    if (RegOpenKeyEx(root, key.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
        throw "Could not open registry key";
    DWORD type;
    DWORD cbData;
    if (RegQueryValueEx(hKey, 
            name.c_str(), NULL, &type, NULL, &cbData) != ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        throw "Could not read registry value";
    }

    std::wstring value;
    if (type == REG_SZ)
    {
        value.resize(1 + (cbData / sizeof(wchar_t)), L'[=11=]');
        if (0 == RegQueryValueEx(hKey, name.c_str(), NULL, NULL,
            reinterpret_cast<BYTE*>(value.data()), &cbData))
        { //okay 
        }
    }
    else if (type == REG_DWORD)
    {
        DWORD dword;
        if (0 == RegQueryValueEx(hKey, name.c_str(), NULL, &type,
            reinterpret_cast<BYTE*>(&dword), &cbData))
            value = std::to_wstring(dword);
    }
    RegCloseKey(hKey);
    return value;
}