读取注册表项,因为字符串返回数字值

时间:2019-04-03 09:40:02

标签: c++ winapi

我正在尝试从注册表中读取Windows“ ProductName”值,我正在使用以下代码来检索该值:

HKEY hKey;
DWORD buffer;
LONG result;
unsigned long type = REG_DWORD, size = 1024;

result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_READ, &hKey);
if (result == ERROR_SUCCESS)
{
    RegQueryValueEx(hKey, "ProductName", NULL, &type, (LPBYTE)&buffer, &size);
    RegCloseKey(hKey);
}

std::stringstream ss;
ss << "version: " << buffer;
std::string s = ss.str();

MessageBox(NULL, s.c_str(), s.c_str(), MB_OK);

我得到的输出是:

Version: 3435973836

,但“ regedit”返回“ Windows 10 Enterprise”。关于为什么我得到这个奇怪值的任何提示?

3 个答案:

答案 0 :(得分:2)

您没有将结果存储在字符串中。

DWORD buffer;
...
RegQueryValueEx(hKey, "ProductName", NULL, &type, (LPBYTE)&buffer, &size);

您应该做的显然是使用字符串:

size_t size = 1024;
char buffer[size];
...

result = RegQueryValueEx(hKey, "ProductName", NULL, &type, buffer, &size);
if(result == ERROR_SUCCESS && type == REG_SZ)
{
  /* do stuff with buffer */
}

答案 1 :(得分:0)

您的缓冲区中没有任何东西:

0xCCCCCCCC : Used by Microsoft's C++ debugging runtime 
             library to mark uninitialised stack memory

In Visual Studio C++, what are the memory allocation representations?

答案 2 :(得分:0)

正如@Lundin所说,您需要发送一个字符串,但不需要发送DWORD的指针。我要添加的是,您得到的值为3435973836(十六进制为0xcccccccc)。这意味着调用RegQueryValueEx失败,甚至没有遇到条件。如果成功,则非Unicode中的buffer的值将类似于16849575270x646E6957)。取决于“ 欠10个企业”的前4个字符,' W '= 0x57;' i '= 0x69;' n '= 0x6e;' d '= 0x64;

“ Windows 10企业版”的产品名称属于本地计算机,但不仅属于当前用户,因此您需要从HKEY_LOCAL_MACHINE中检索它。

相关问题