# RegCreateKeyEx Function

`Declare Function RegCreateKeyEx Lib "advapi32.dll" Alias "RegCreateKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal Reserved As Long, ByVal lpClass As String, ByVal dwOptions As Long, ByVal samDesired As Long, lpSecurityAttributes As SECURITY_ATTRIBUTES, phkResult As Long, lpdwDisposition As Long) As Long`

RegCreateKeyEx creates a new registry key. If the key you want to create already exists, the existing key will be open (as if RegOpenKeyEx had been used). The handle to the created/opened key is put into the variable passed as phkResult. The function returns 0 if successful, or a non-zero error code if an error occurs.

hKey
  Either a handle to an open registry key or one of the registry base key flags to create the new key under.
lpSubkey
  The name of the new key to create.
Reserved
  Reserved. Set to 0.
lpClass
  The name of the class or object type of the key. You can specify an empty string.
dwOptions
  Set to 0 if you want the key to be saved to the registry. Set to 1 if you want the key to be destroyed when Windows shuts down (i.e., do not save).
samDesired
  One or more of the regsitry access flags specifying the desired read/write access.
lpSecurityAttributes
  For Windows NT, the level of security to give the key. For other versions of Windows, set its members to zero.
phkResult
  Variable that receives the handle to the new/opened registry key.
lpdwDisposition
  Variable that receives 1 if a new key was created, or 2 if an already-existing key was opened.

Example:

    ' Create and set the Data value under the key:
    ' HKEY_CURRENT_USER\Software\Dummy\DummyApp\1.0\
    Dim secattr As SECURITY_ATTRIBUTES
    ' The next three lines give default values for secattr
    secattr.lpSecurityDescriptor = 0  ' default security level
    secattr.bInheritHandle = True  ' might as well allow it
    secattr.nLength = Len(secattr)  ' store size of variable
    subkey = "Software\Dummy\DummyApp\1.0"  ' key name
    x = RegCreateKeyEx(HKEY_CURRENT_USER, subkey, 0, "", 0, KEY_READ, secattr, hregkey, newopen)
    ' if created, newopen = 1; if not, newopen = 2
    If x <> 0 Then  ' error creating key -- abort!
      Debug.Print "Could not open registry key."
      Exit Sub
    End If
    '(put rest of code here)
    x = RegCloseKey(hregkey)

Related Calls: RegCloseKey, RegOpenKeyEx
Category: Registry
Back to the index.