C and C++ New registry key code example

  • 2020-06-12 10:12:53
  • OfStack

Use the RegCreateKeyEx function in the Windows API function to create a new registry key.

RegCreateKeyEx function:


 Prototype: LONG RegCreateKeyEx( 
   HKEY hKey,  //  Name of the primary key  
   LPCTSTR lpSubKey,  //  The child key name or path  
   DWORD Reserved,  //  Reserved for 0 
   LPTSTR lpClass,  // 1 A set to NULL
   DWORD dwOptions,  
     /*  Student: for the bond that you set up 1 Some options can be these values: REG_OPTION_NON_VOLATILE . REG_OPTION_VOLATILE .    REG_OPTION_BACKUP_RESTORE The first 1 It's the default. 1 As with the first 1 Just one. */ 
   REGSAM samDesired, //  Set your access to the key you created 
   LPSECURITY_ATTRIBUTES lpSecurityAttributes, 
     //1 A set to NULL
   PHKEY phkResult,  //  Returns a handle to a new registry key  
   LPDWORD lpdwDisposition // Open for viewing 1 I have an existing key, or I have a new one  
  
); 

Return value: non-0 if unsuccessful, ERROR_SUCCESS if successful.

Opens the specified key or child key. If the key you want to open does not exist, this function will try to create it. When creating or opening registry keys, you need to specify access rights, and these access rights need to level 1. The default permission is KEY_ALL_ACCESS. There is also KEY_CREATE_LINK to create character chains,KEY_CREATE_SUB_KEY to create child keys,KEY_EXECUTE to read keys, KEY_NOTIFY to change key notifications, KEY_QUERY_VALUE to query key values, KEY_SET_VALUE to set data values. Note that keys cannot be built at the root 1 level; only predefined keys can be created at the root 1 level of the registry. Please refer to the online manual for specific usage.

See Microsoft's official documentation: http: / / msdn microsoft. com/zh - cn/aa911940

Code examples:


# include <windows.h>
# include <tchar.h>
int main(void)
{
 HKEY hKey = NULL;
 TCHAR * subKey = _T("SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\2345PCSafe\\test");
 DWORD dwOptions = REG_OPTION_NON_VOLATILE;
 DWORD dwDisposition;
 long resulte = RegCreateKeyEx(HKEY_LOCAL_MACHINE, subKey, 0, NULL,
 dwOptions, KEY_WRITE, NULL, &hKey, &dwDisposition);
 if (resulte != ERROR_SUCCESS)
 {
 MessageBox(NULL, _T(" Failed to open the registry "), _T(" prompt "), MB_OK);
 }
 else
 {
 if (dwDisposition == REG_OPENED_EXISTING_KEY)
 {
 MessageBox(NULL, _T(" Open the 1 Three existing registry keys "), _T(" prompt "), MB_OK);
 }
 else if (dwDisposition == REG_CREATED_NEW_KEY)
 {
 MessageBox(NULL, _T(" new 1 Three registry keys "), _T(" prompt "), MB_OK);
 }
 }
 return 0;
}

conclusion


Related articles: