Nakruf
Nakruf

Reputation: 17

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;

}

Upvotes: 0

Views: 3048

Answers (1)

Seva Alekseyev
Seva Alekseyev

Reputation: 61378

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));

Most importantly, HKEY_LOCAL_MACHINE is read-only for non-admin users, and even for admin users it's read-only without privilege elevation.

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

Upvotes: 2

Related Questions