Nakruf Nakruf - 15 days ago 5
C++ Question

RegSetValueEx doesn't create a String Value

I read some documentation and looked at code examples but I can't find any reasons for my code not to work.

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

void AddSubKeyWithValue(HKEY hRootKey, LPWSTR strSubKey, LPCTSTR StringVal, LPCTSTR data)
{
HKEY hKey;
RegOpenKeyEx(hRootKey, strSubKey, NULL, KEY_ALL_ACCESS, &hKey);
RegSetValueEx(hRootKey, StringVal, NULL, REG_SZ, (LPBYTE)&data, sizeof(REG_SZ));
RegCloseKey(hKey);
return;
}


void main() {

AddSubKeyWithValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",L"Slayer Tool", L"c:\\Slayer\\Update.exe");

system("pause");
return;

}

Answer

The RegSetValueEx call is all off. The first parameter should be a subkey handle, not HKEY_LOCAL_MACHINE. The 5th parameter should point to the data, not to the pointer to data. The 6th parameter should contain the string length, in bytes (keep in mind it's a wide string), including the terminating null.

So reformulate like this:

RegSetValueEx(hKey, StringVal, NULL, REG_SZ, (LPBYTE)data, sizeof(wchar_t)*(wcslen(data)+1));

Also, system("pause") is an awful way to wait for a key press. Call "getch()" instead.