I am trying to write to the Windows Registry using the Win32 API, but for some reason when I try writing bytes to a Registry key with the REG_BINARY
data type, the key value does not change.
Here is code that attempts to write to the Registry key:
struct angles
{
float pitch;
float yaw;
float roll;
};
int main()
{
angles ang;
ang.pitch = 69.25;
ang.yaw = 420.21;
ang.roll = 100.0;
unsigned char b[sizeof(ang)];
std::cout << "Size of structure: " << sizeof(ang) << "\n\n";
memcpy(b, &ang, sizeof(ang));
for (int i = 0; i < sizeof(b); i++)
{
printf("Byte %d == %02X ", i, b[i]);
std::cout << "\n\n";
}
HKEY handle;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_WRITE, &handle) == ERROR_SUCCESS)
{
if (RegSetValueEx(handle, L"test", 0, REG_BINARY, (BYTE*)&b, sizeof(b)) == ERROR_SUCCESS)
{
std::cout << "Wrote to key test.\n\n";
}
else
{
std::cout << "Couldnt write key\n";
}
}
else
std::cout << "couldn't open key\n";
while (!GetAsyncKeyState(VK_NUMPAD0))
{
}
return 0;
}
If you compile the code, you'll see that I am copying the bytes of the angles struct into the char array b
.
When calling RegOpenKeyEx()
, it succeeds. And when calling RegSetValueEx()
, it succeeds. But, the value in the Registry does not change.
So, I'm not sure what to do at this point. I am running the application as admin as well.
Copyright Notice:Content Author:「Ballers」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/63254655/cant-write-char-array-to-windows-registry-key