c++ RegSetValueEx sets only one char value in registry

17,363

Solution 1

strlen(data) is probably returning a value of 1, as strlen expects a char* and L"TestData\0" is wide. Use TEXT("TestData\0") and call _tcslen(data).
Note that RegSetValueEx expects the sizeof the data, so use _tcslen(data) * sizeof(TCHAR)

Solution 2

replace the L"TestData" by _T("TestData"); and strlen(data)+1 by tcslen(data) * sizeof(TCHAR));

so your code looks like this :

LPCTSTR value = TEXT("SomeKey");
LPCTSTR data = TEXT("TestData");

LONG setRes = RegSetValueEx(hKey, value, 0, REG_SZ, (LPBYTE)data, _tcslen(data) * sizeof(TCHAR));

Solution 3

Where are you casting data?

Either way, it looks like you may be working with wide characters, but you seem to be using "plain old" strlen - instead of wcslen or some other function intended to work with wide-character strings.

Share:
17,363

Related videos on Youtube

Tom
Author by

Tom

Updated on May 12, 2022

Comments

  • Tom
    Tom almost 2 years

    I'm casting (char * ) on data and i'm getting only one char value in the registry. if i don't use the casting msvc 2010 tells me that the argument type LPCTSTR is incompatible with const char *.

    can someone help me?

    HKEY hKey;
    LPCTSTR sk = TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
    
    LONG openRes = RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_ALL_ACCESS , &hKey);
    
    if (openRes==ERROR_SUCCESS) {
        printf("Success opening key.");
    } else {
        printf("Error opening key.");
    }
    
    LPCTSTR value = TEXT("SomeKey");
    LPCTSTR data = L"TestData\0";
    
    LONG setRes = RegSetValueEx (hKey, value, 0, REG_SZ, (LPBYTE)data, strlen(data)+1);
    
    if (setRes == ERROR_SUCCESS) {
        printf("Success writing to Registry.");
    } else {
        printf("Error writing to Registry.");
    }
    cout << setRes << endl;
    
    LONG closeOut = RegCloseKey(hKey);
    if (closeOut == ERROR_SUCCESS) {
        printf("Success closing key.");
    } else {
        printf("Error closing key.");
    }
    
  • zenzelezz
    zenzelezz over 13 years
    Looks like a better explanation/suggestion than mine :)
  • Tom
    Tom over 13 years
    when i try to use this, for example LPCTSTR data = TEXT("ThisIsTheValueIWant\0"); then i get in registry only "ThisIsTheV" what should i do?
  • Joel Rondeau
    Joel Rondeau over 13 years
    Answer modified to take this into account.