Jenifer22
Jenifer22

Reputation: 13

trying to create a value in registry - C++ - RegSetValueEx

I tried to add a value to registry in c++, but the program shows error. I have a very simple code, when the program run I got the error: Unable to set registry value value_name (RegSetValueEx failed)

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <Windows.h>

using namespace std;


int main() {


    HKEY key;
    if (RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion"), &key) != ERROR_SUCCESS)
    {
        cout << "unable to open registry";
    }



    if (RegSetValueEx(key, TEXT("value_name"), 0, REG_SZ, (LPBYTE)"value_data", strlen("value_data")*sizeof(char)) != ERROR_SUCCESS)
    {
        RegCloseKey(key);
        cout << "Unable to set registry value value_name";
    }
    else
    {
        cout << "value_name was set" << endl;
    }

}

Upvotes: 1

Views: 2827

Answers (2)

David Heffernan
David Heffernan

Reputation: 613582

There are a few reasons why this might fail:

  1. You need to have administrator rights to modify keys and values under HKLM. You'll need to make sure that your process runs elevated. Typically that means specifying the requireAdministrator option to your manifest.
  2. Your anti-malware software is blocking your attempts to write to this key.

The other factor that might well confuse you is the registry redirector. Once you get the value being written you might not be able to find it. For a 32 bit process running on a 64 bit system, the redirector will store the value in the 32 bit view. That 32 bit view lives under HKLM\Software\Wow6432Node.

When debugging problems like this, it pays to read the documentation carefully regarding error handling. In this case, RegSetValueEx returns a Win32 error code. If that value is not equal to ERROR_SUCCESS then the function call failed. However, the specific value returned indicates why the call failed.

One final point to make is that you should be using RegOpenKeyEx rather than the long deprecated RegOpenKey.

Upvotes: 1

Cristian Niculescu
Cristian Niculescu

Reputation: 445

You need to Run as Administrator, or elevated, to make changes to HKLM. Try either that (you can run Visual Studio as admin to debug via F5) or work under HKEY_CURRENT_USER instead.

Upvotes: 1

Related Questions