Search code examples
c++mfcregistry

I use CRegKey to open some, but this m_hKey != 0


I want to get JDk path by the Registry, this path is:

HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Development Kit\\1.8

when I use:

CRegKey.open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\JavaSoft\\Java Development Kit\\1.8")

it throws expression m_hKey != 0. so what's happening ? How to fix this bug?

Here is my code:

// Get Java environment variable install path
CRegKey key;
wchar_t JavaHome[40];
ULONG szJavaHome = 40;
bool rest = key.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\JavaSoft\\Java Development Kit\\1.8");
if (key.m_hKey == 0)
    MessageBox(L"11");
rest = key.QueryStringValue(L"JavaHome", JavaHome, &szJavaHome);

Solution

  • You cannot simply use the CRegKey variable key after trying to Open it, without checking the return value of it.

    auto retOpenKey = key.Open(...); //LONG not bool
    if (ERROR_SUCCESS == retOpenKey)
    {
        //Ok do stuff with key
    }
    else
        auto err = GetLastError();
    

    System error codes and / or FormatMessage

    You can also look in the implementation of the function, and debug in there, as it is inline in the header:

    inline LONG CRegKey::Open(
        _In_ HKEY hKeyParent,
        _In_opt_z_ LPCTSTR lpszKeyName,
        _In_ REGSAM samDesired) throw()
    {
        ATLASSUME(hKeyParent != NULL);
        HKEY hKey = NULL;
        LONG lRes = m_pTM != NULL ?
            m_pTM->RegOpenKeyEx(hKeyParent, lpszKeyName, 0, samDesired, &hKey) :
            RegOpenKeyEx(hKeyParent, lpszKeyName, 0, samDesired, &hKey);
        if (lRes == ERROR_SUCCESS)
        {
            lRes = Close();
            ATLASSERT(lRes == ERROR_SUCCESS);
            m_hKey = hKey;
    #if WINVER >= 0x0501
            m_samWOW64 = samDesired & (KEY_WOW64_32KEY | KEY_WOW64_64KEY);
    #endif
        }
        return lRes;
    }