I thought I knew this but I don't.

Currently I use RegCreateKeyEx to create a key, and then I call RegSetValueEx.

Now what happens is that I create another key (folder in the regedit GUI), and I set the default value for that key (folder).

But how do I add a simple string value (not a sub folder) to that key?

Very roughly I do

RegCreateKeyEx (hKey,
                pszSubKey,
                0,    // ulOptions, must be 0
                NULL, // address of class string
                REG_OPTION_NON_VOLATILE, // special options flag
                KEY_ALL_ACCESS,        // desired security access
                NULL, // address of key security structure
                &hSubKey,          // address of buffer for opened 
                &ActionDone) ;

(void)RegCloseKey(hKey);

RegSetValueEx (hSubKey,
               L"", 
               0,  // reserved
               REG_SZ,
               (const BYTE*)pszData,  // address of value data
               ikByteCount);

...hope its clear....


Owen F. Ransen
Easy to use graphics effects:

Dani AI

Generated

Short answer: pass a non-empty value name to RegSetValueEx (the empty string or NULL targets the key's "(Default)" value). Use the HKEY returned by RegCreateKeyEx for the subkey, give the right byte count (including the terminating NUL), check the return code, then close the subkey handle.

Example (Unicode build):

const wchar_t *data = L"Hello world";
DWORD cb = (DWORD)((wcslen(data) + 1) * sizeof(wchar_t));
LONG rc = RegSetValueExW(hSubKey, L"MyValueName", 0, REG_SZ, (const BYTE*)data, cb);
if (rc != ERROR_SUCCESS) { /* handle error */ }
RegCloseKey(hSubKey);

Portability notes and common pitfalls: calculate bytes, not characters — (wcslen+1)*sizeof(wchar_t) for wide strings or (strlen+1) for ANSI. If you use TCHAR, use _tcslen and sizeof(TCHAR). Don’t forget to close hSubKey. Open the key with only the access you need (e.g., KEY_SET_VALUE or KEY_WRITE) instead of KEY_ALL_ACCESS. If writing under HKLM on modern Windows, watch for permission issues and Wow64 redirection (use KEY_WOW64_64KEY or KEY_WOW64_32KEY when appropriate).

Alternatives and troubleshooting: on Vista+ you can use RegSetKeyValue for a slightly simpler call (no separate open/close in simple cases). If RegSetValueEx fails, log the returned LONG (ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, etc.). As pointed out, the MSDN docs cover the parameters and error codes — use them for exact behavior. This addresses the question from : give a non-empty string as the value name to create a named string value.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.