如何:将数据写入 Windows 注册表 (C++/CLI)

下面的代码示例使用 CurrentUser 项创建一个对应于 Software 项的 RegistryKey 类的可写实例。 然后使用 CreateSubKey 方法创建一个新项并将其添加到项/值对中。

示例

bwt6b955.collapse_all(zh-cn,VS.110).gif代码

// 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;
}

备注

可以使用 .NET Framework 通过 RegistryRegistryKey 类访问注册表,这两个类都在 Microsoft.Win32 命名空间中定义。 Registry 类是 RegistryKey 类的静态实例的容器。 每个实例表示一个根注册表节点。 这些实例为 ClassesRootCurrentConfigCurrentUserLocalMachineUsers

请参见

概念

如何:从 Windows 注册表中读取数据 (C++/CLI)

其他资源

编程在Visual C++的.NET