Search code examples
c++registrykey

C++ Why does my code put a registry key at the wrong directory?


So, I want to put a registry key at the directory HKCU\Software\Microsoft\Windows\CurrentVersion\Run, and I want it to be called Test, and have it contain "TestText", but instead this code puts a new key at HKCU\Test and the program writes random Chinese characters in the registry key. Anyone help?

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <string>
#include <time.h>
using namespace std;

int main()
{
     HKEY keyExample;

    if (RegOpenKey(HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Run\\"), &keyExample) != ERROR_SUCCESS)
    {
        RegCloseKey(keyExample);
        return 69;
    }
     if (RegSetKeyValue(HKEY_CURRENT_USER, TEXT("Test"), 0, REG_SZ, (LPBYTE)"TestText", strlen("TestText")*sizeof(char)) != ERROR_SUCCESS)
     {
         RegCloseKey(keyExample);
         cout << "Unable to set registry value value_name";
     }

     RegCloseKey(keyExample);
     return 0;
}

Solution

  • RegSetKeyValue(HKEY_CURRENT_USER, ...
    

    This is the bug. You need to use the keyExample you got when you opened the key you wanted. Like this:

    RegSetKeyValue(keyExample, ...
    

    And for your ANSI/Unicode problem, you need to use the TEXT() macro for your actual data, not just its name:

    RegSetKeyValue(keyExample, TEXT("Test"), 0, REG_SZ, TEXT("TestText"), lstrlen(TEXT("TestText"))*sizeof(TCHAR))
    

    It's generally easier to forget all the legacy backward compatible stuff related to the TEXT/TCHAR menus and to directly call the W versions of the Windows API functions with long strings.