Setting a DWORD value in the registry

24,973

Solution 1

The biggest error is in (const BYTE*)0x00: you are casting 0x00 to a BYTE *, which means that basically you are passing a NULL pointer. Instead, you should create a DWORD variable, put the value you want to store in the registry in it and pass a pointer to it instead of that 0x00.

Also, you must change REG_SZ to REG_DWORD if you want to store a DWORD value, otherwise the DWORD will be interpreted as a (somewhat strange) string.

RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\pager", 0, KEY_ALL_ACCESS, &hKey);
DWORD value=0;
RegSetValueEx(hKey, TEXT("Save"), 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
RegCloseKey(hKey);

But, most importantly, you should really check the return values of these functions: now you're just "hoping" they work, ignoring any failure and continuing with the instruction flow, which can lead to unexpected situations.

If you checked the error codes you would have noticed immediately that it is the RegSetValueEx function that fails, and the error code may have been something like "invalid parameter", that would have pointed you in the right direction.

Solution 2

For the dwType parameter to RegSetValueEx, you should be using REG_DWORD instead of REG_SZ.

You should also be passing a valid pointer to a DWORD for the lpData parameter.

Solution 3

Change your REG_SZ parameter to REG_DWORD. That parameter specifies the type of the value that will be written to the registry.

See http://msdn.microsoft.com/en-us/library/ms724884(v=vs.85).aspx for a full list of types.

Share:
24,973
Adrian
Author by

Adrian

Updated on August 07, 2020

Comments

  • Adrian
    Adrian over 3 years

    I'm trying to set a DWORD value in the registry. I made it work with a text value, but now I want to set another value with a numeric one(0). But it doesnt write it.
    This is my code:

    RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\pager", 0, KEY_ALL_ACCESS, &hKey);
    RegSetValueEx(hKey, TEXT("Save"), 0, REG_SZ, (const BYTE*)0x00, sizeof(DWORD));
    RegCloseKey(hKey);
    

    PS: the key already exist with the value 1 so I'm trying to overide it with the value 0(I'm not creating a new one).

  • Adrian
    Adrian about 13 years
    i changed it, but still no changes, it doesnt set the value 0
  • Peter Huene
    Peter Huene about 13 years
    As Matteo suggests, you should be checking for failure and calling GetLastError to determine what's wrong (if you're using Visual C++ and debugging, you can use the pseudo-register "@err" to show the current last error value).