开发者

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, "Soft开发者_如何学编程ware\\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).


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜