Setting the DWORD value in the registry

I am trying to set the DWORD value in the registry. I made it work with a text value, but now I want to set another value with a numeric (0). But it does not write. 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 exists with a value of 1, so I'm trying to redefine it with a value of 0 (I am not creating a new one).

+4
source share
3 answers

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

In addition, you must change REG_SZ to REG_DWORD if you want to keep the DWORD , otherwise the DWORD will be interpreted as a (somewhat weird) 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 just “hope” that they work, ignoring any failure and continuing the flow of commands, which can lead to unforeseen situations.

If you checked the error codes, you would immediately notice that the RegSetValueEx function does not work, and the error code may be something like an “invalid parameter” that would point you in the right direction.

+16
source

For the dwType RegSetValueEx parameter, you must use REG_DWORD instead of REG_SZ .

You must also pass a valid DWORD pointer for the lpData parameter.

+3
source

Change the REG_SZ parameter to REG_DWORD. This parameter indicates the type of value that will be written to the registry.

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

+2
source

Source: https://habr.com/ru/post/1345275/


All Articles