Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

c++ - Setting a DWORD value in the registry

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...