Newbie
Newbie

Reputation: 1613

How to set a value in windows registry? (C++)

I want to edit key "HKEY_LOCAL_MACHINE\Software\company name\game name\settings\value" to "1" (DWORD)

This is my code:

HKEY hkey;
 DWORD dwDisposition;
 if(RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\company name\\game name\\settings"), 0, NULL, 0, 0, NULL, &hkey, &dwDisposition) == ERROR_SUCCESS){
  DWORD dwType, dwSize;
  dwType = REG_DWORD;
  dwSize = sizeof(DWORD);
  DWORD rofl = 1;
  RegSetValueEx(hkey, TEXT("value"), 0, dwType, (PBYTE)&rofl, dwSize); // does not create anything
  RegCloseKey(hkey);
 }

But it doesnt do anything. RegCreateKeyEx() is the only function that actually does something: creates the "folders" in the registry only. So once again how im failing? How i can create "files" in the registry?

Upvotes: 4

Views: 19814

Answers (3)

Stephen C. Steel
Stephen C. Steel

Reputation: 4430

You probably need to pass in KEY_WRITE as the value of the samDesired arugment to RegCreateKeyEx() function (sixth argument).

Upvotes: 1

Notinlist
Notinlist

Reputation: 16650

This is a copy and edit from an actual code, may contain errors.

LONG
SetRegValue
    (
        const wchar_t* path
        ,const wchar_t *name
        ,const wchar_t *value
    )
{
    LONG status;
    HKEY hKey;

    status = RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_ALL_ACCESS, &hKey);
    if ( (status == ERROR_SUCCESS) && (hKey != NULL))
    {
        status = RegSetValueEx( hKey, name, 0, REG_SZ, (BYTE*)value, ((DWORD)wcslen(value) + 1)*sizeof(wchar_t));
        RegCloseKey(hKey);
    }
    return status;
}

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 942197

Always check the return value of API functions. You'll see that RegSetValueEx() returns 5, access denied. You didn't ask for write permission. Fix:

  if(RegCreateKeyEx(HKEY_LOCAL_MACHINE, 
      TEXT("Software\\company name\\game name\\settings"), 
      0, NULL, 0, 
      KEY_WRITE, NULL, 
      &hkey, &dwDisposition) == ERROR_SUCCESS) {
    // etc..
  }

Upvotes: 11

Related Questions