Partager via


How to: Write Data to the Windows Registry (C++/CLI)

The following code example uses the CurrentUser key to create a writable instance of the RegistryKey class corresponding to the Software key. The CreateSubKey method is then used to create a new key and add to key/value pairs.

Example

Code

// registry_write.cpp
// compile with: /clr
using namespace System;
using namespace Microsoft::Win32;

int main()
{
   // The second OpenSubKey argument indicates that
   // the subkey should be writable. 
   RegistryKey^ rk;
   rk  = Registry::CurrentUser->OpenSubKey("Software", true);
   if (!rk)
   {
      Console::WriteLine("Failed to open CurrentUser/Software key");
      return -1;
   }

   RegistryKey^ nk = rk->CreateSubKey("NewRegKey");
   if (!nk)
   {
      Console::WriteLine("Failed to create 'NewRegKey'");
      return -1;
   }

   String^ newValue = "NewValue";
   try
   {
      nk->SetValue("NewKey", newValue);
      nk->SetValue("NewKey2", 44);
   }
   catch (Exception^)
   {
      Console::WriteLine("Failed to set new values in 'NewRegKey'");
      return -1;
   }

   Console::WriteLine("New key created.");
   Console::Write("Use REGEDIT.EXE to verify ");
   Console::WriteLine("'CURRENTUSER/Software/NewRegKey'\n");
   return 0;
}

Remarks

You can use the .NET Framework to access the registry with the Registry and RegistryKey classes, which are both defined in the Microsoft.Win32 namespace. The Registry class is a container for static instances of the RegistryKey class. Each instance represents a root registry node. The instances are ClassesRoot, CurrentConfig, CurrentUser, LocalMachine, and Users.

See Also

Concepts

How to: Read Data from the Windows Registry (C++/CLI)

Other Resources

.NET Programming in Visual C++