Search code examples
c++winapiregistrydword

How to write a 32 Bit D-Word to Windows registry in C++


I am trying to disable the Windows Defender using a C++ Win32API application. To do that I need to write a D Word into the registry (DisableAntiSpyware = 1). I always do that manually after installing a new Windows. So here is my code, but its not working. Maybe someone could tell me why or what is wrong with it. Thank you!

OK I've changed the code a bit, still not working...

        case 1:

            //::MessageBeep(MB_ICONERROR);
            ::MessageBox(hWnd, L"Button was Pressed",L"Button was clicked?",MB_OK);

            LONG
            SetRegValue
            (
            const wchar_t* path
            , const wchar_t *name
            , const BYTE *value

                );
            {
                LONG status;
                HKEY hKey;

                DWORD value = 0x00000001;

                status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"\\SOFTWARE\\Policies\\Microsoft\\Windows Defender", 0, KEY_ALL_ACCESS, &hKey);
                if ((status == ERROR_SUCCESS) && (hKey != NULL))
                {
                    status = RegSetValueEx(hKey, L"test", 0, REG_DWORD, (const BYTE*)&value,sizeof(value));
                    RegCloseKey(hKey);
                }
                return status;

                ::MessageBeep(MB_ICONERROR);
            }
        }
    }
    break;

Solution

  • When opening a Registry key, you should request only the rights you actually need. So replace KEY_ALL_ACCESS with KEY_SET_VALUE instead, since all you are doing is writing a value. But even then, you might still need to run your app with elevated permissions in order to write to HKEY_LOCAL_MAHCINE, unless you give your user account write access to the Windows Defender key beforehand.

    Also, if your code is compiled as 32bit and runs on a 64bit system, and it needs to write to the 64bit Registry, then you have to include the KEY_WOW64_64KEY flag otherwise you may be subject to Registry Reflection/Registry Redirection.

    Try something more like this instead:

    case 1:
    {
        ::MessageBox(hWnd, L"Button was Pressed", L"Button was clicked?", MB_OK);
    
        DWORD value = 1;
        DWORD flags = KEY_SET_VALUE;
    
        #if !defined(_WIN64)
        BOOL bIsWow64Process = FALSE;
        if (IsWow64Process(GetCurrentProcess(), &bIsWow64Process) && bIsWow64Process)
            flags |= KEY_WOW64_64KEY;
        #endif
    
        HKEY hKey;
        LONG status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"\\SOFTWARE\\Policies\\Microsoft\\Windows Defender", 0, flags, &hKey);
        if ((status == ERROR_SUCCESS) && (hKey != NULL))
        {
            status = RegSetValueEx(hKey, L"DisableAntiSpyware", 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
            RegCloseKey(hKey);
        }
    
        ::MessageBeep(MB_ICONERROR);
    }
    break;