views:

346

answers:

1

I am playing with the registry programmatically for the first time, and it's not working that well (but at least I haven't destroyed my computer). Specifically, I keep getting back Error 5 (Access is Denied) from RegCreateKeyEx and RegSetValueEx. The thing that is strangest to me is that when HKEY_CURRENT_USER\Software\dir1\Sub Directory already exists, RegCreateKeyEx fails with Error 5, but when it doesn't already exist, it creates it successfully; and then fails on the RegSetValueEx.

Am I doing anything wrong in this code?

BOOL MyDialog::SaveLocationsToRegistry()
{
    HKEY   hkey;
    DWORD  dwDisposition;
    DWORD dwType, dwSize;
    LONG result = RegCreateKeyEx(HKEY_CURRENT_USER, TEXT("Software\\dir1\\Sub Directory"), 
                                 0, NULL, 0, 0, NULL, &hkey, &dwDisposition);
    if(result == ERROR_SUCCESS)
    {
        LPCTSTR szLastFolder = "C:\\Documents and Settings\\user\\My Documents\\Copy of item\0";
        dwType = REG_SZ;
        dwSize = strlen(szLastFolder)+1;
        LONG setResult = RegSetValueEx(hkey, TEXT("LastFolder"), 0, dwType, 
        (PBYTE)&szLastFolder, dwSize);
        RegCloseKey(hkey);
        return setResult == ERROR_SUCCESS;
    }
    else
    {
        return false;
    }
}

Note: The absolute path is only there temporarily. Baby steps ;-)

+6  A: 

You're not asking for any access rights. You probably want to specify KEY_WRITE (or something) for the 6th parameter (samDesired).

LONG result = RegCreateKeyEx(HKEY_CURRENT_USER, TEXT("Software\\dir1\\Sub Directory"),
                 0, NULL, 0, KEY_WRITE, NULL, &hkey, &dwDisposition);
Michael Burr
Thanks! I'm now getting gibberish saved into my registry... but it's something :-)
Smashery
The gibberish turned out to be an incorrect level of indirection or something like that. Thanks again for your help!
Smashery