C ++从注册表获取Windows产品ID

时间:2016-02-09 15:41:16

标签: c++ winapi registry

我已经在互联网上搜索了很多"解决方案"哪个对我不起作用:/

我有这个:

HKEY keyHandle;
char rgValue[1024];
char fnlRes[1024];
DWORD size1;
DWORD Type;

if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", 0, KEY_QUERY_VALUE | KEY_WOW64_64KEY, &keyHandle) == ERROR_SUCCESS)
{
    size1 = 1023;
    RegQueryValueEx(keyHandle, L"Productid", NULL, &Type, (LPBYTE)rgValue, &size1);
    sprintf_s(fnlRes, "Product ID of your Windows system is:: %s", rgValue);
}
else strcpy_s(fnlRes, "Couldn't access system information!");

RegCloseKey(keyHandle);

std::cout << fnlRes;

我在控制台中得到了这个:

Screenshot

1 个答案:

答案 0 :(得分:3)

原因是字符编码不匹配。您正在调用RegQueryValueEx()的Unicode版本,但为其提供了一个Ansi缓冲区来填充。使用WCHAR代替char

HKEY keyHandle;
WCHAR rgValue[1024];
WCHAR fnlRes[1024];
DWORD size1;
DWORD Type;

if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", 0, KEY_QUERY_VALUE | KEY_WOW64_64KEY, &keyHandle) == ERROR_SUCCESS)
{
    size1 = 1023;
    RegQueryValueExW(keyHandle, L"Productid", NULL, &Type, (LPBYTE)rgValue, &size1);
    swprintf_s(fnlRes, L"Product ID of your Windows system is:: %s", rgValue);
    RegCloseKey(keyHandle);
}
else wcscpy_s(fnlRes, L"Couldn't access system information!");

wcout << fnlRes;