簡體   English   中英

從 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'\0');
    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'\0');
    
    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'\0');
        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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM