Search code examples
c++winapiregistry

C++ get windows product id from registry


I already searched the internet and found a lot of "solutions" which dont work for me :/

I have this:

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;

And I get this in console:

Screenshot


Solution

  • The reason is a character encoding mismatch. You are calling the Unicode version of RegQueryValueEx() but giving it an Ansi buffer to fill. Use WCHAR instead of 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;