使用c ++创建一个新的Windows注册表项

Bri*_*ney 14 c++ registry

我正在尝试使用C++在Windows注册表中创建一个新的注册表项.这是我到目前为止的代码:

HKEY hKey;
    LPCTSTR sk = TEXT("SOFTWARE\\OtherTestSoftware");

    LONG openRes = RegCreateKeyEx(
            HKEY_LOCAL_MACHINE,
            sk,
            0,
            NULL,
            REG_OPTION_BACKUP_RESTORE,
            KEY_ALL_ACCESS,
            NULL,
            &hKey,
            NULL);

    if (openRes==ERROR_SUCCESS) {
        printf("Success creating key.");
    } else {
        printf("Error creating key.");
    }

    LPCTSTR value = TEXT("OtherTestSoftwareKey");
    LPCTSTR data = "OtherTestData\0";

    LONG setRes = RegSetValueEx (hKey, value, 0, REG_SZ, (LPBYTE)data, strlen(data)+1);

    if (setRes == ERROR_SUCCESS) {
        printf("Success writing to Registry.");
    } else {
        printf("Error writing to Registry.");
    }

    //RegDeleteKey(hKey, sk);

    LONG closeOut = RegCloseKey(hKey);

    if (closeOut == ERROR_SUCCESS) {
        printf("Success closing key.");
    } else {
        printf("Error closing key.");
    }
Run Code Online (Sandbox Code Playgroud)

我能够使用非常相似的代码片段成功打开现有密钥(基本上用RegOpenKeyEx替换RegCreateKeyEx).我会想象我传递给RegCreateKeyEx的一个或多个参数导致了麻烦.我真的不确定哪些事情可能会被搞砸,因为我所困的所有错误代码都显示成功.作为参考,这是RegCreateKeyEx的函数签名:

/*
 * LONG WINAPI RegCreateKeyEx(
      __in        HKEY hKey,
      __in        LPCTSTR lpSubKey,
      __reserved  DWORD Reserved,
      __in_opt    LPTSTR lpClass,
      __in        DWORD dwOptions,
      __in        REGSAM samDesired,
      __in_opt    LPSECURITY_ATTRIBUTES lpSecurityAttributes,
      __out       PHKEY phkResult,
      __out_opt   LPDWORD lpdwDisposition
    );
 */
Run Code Online (Sandbox Code Playgroud)

任何想法都会很棒!

谢谢,布赖恩

NTD*_*DLS 16

我多年来一直在编写自己的个人函数库.其中一部分完全涉及注册表访问,请参阅Registry.Cpp文件的CreateRegistryKey函数.

如果您有兴趣,可以在这里获取整个图书馆.


Gre*_*ill 2

第一条线索是您对REG_OPTION_BACKUP_RESTORE. 您可能不想使用该标志,因为我相信它需要您事先启用的特殊“备份”权限。普通应用程序不会愿意这样做。