Skip to content

CreateKey

A snippet that creates a new registry key under HKEY_CLASSES_ROOT with RegCreateKeyEx.

Published Nov 28, 1996

The shortest correct way to create a registry key programmatically: RegCreateKeyEx with REG_OPTION_NON_VOLATILE and KEY_WRITE, then close the handle on success. The example drops a subkey under HKEY_CLASSES_ROOT* - in real code you would target your own product key and check the return value for ERROR_SUCCESS before assuming it was created (or note that dwFunc tells you whether the key already existed). Use it as the reference call whenever an installer or first-run routine needs to lay down registry structure.

#include <Stdio.H>
#include <Stdlib.H>
#include <Windows.H>

//////////////////////////////////////////////////////////////////////

int main()
{
    HKEY hKey;
    DWORD dwFunc;
    LONG Result;
    Result = RegCreateKeyEx(HKEY_CLASSES_ROOT,"*\\New Key",0,(LPTSTR)NULL,REG_OPTION_NON_VOLATILE,KEY_WRITE,(LPSECURITY_ATTRIBUTES)NULL,&hKey,&dwFunc);

    if(Result==ERROR_SUCCESS)
    {
        RegCloseKey(hKey);
        hKey = (HKEY)NULL;
        return 1;
    }
    return 0;
}

//////////////////////////////////////////////////////////////////////
An unhandled error has occurred. Reload 🗙