c++ 读写注册表

发布时间 2023-09-21 11:26:01作者: laremehpe
class CConfig
{
    HKEY _hKey;
public:
    ~CConfig()
    {
        if (_hKey)
        {
            RegCloseKey(_hKey);
        }
    }

    CConfig() : _hKey(0)
    {
    }

    LSTATUS Save(
        PCWSTR lpValueName,
        DWORD dwType,
        const void* lpData,
        DWORD cbData)
    {
        return RegSetValueExW(_hKey, lpValueName, 0, dwType, (BYTE*)lpData, cbData);
    }

    LSTATUS Load(
        PCWSTR lpValueName,
        PDWORD lpType,
        void* lpData,
        PDWORD lpcbData)
    {
        return RegQueryValueExW(_hKey, lpValueName, 0, lpType, (BYTE*)lpData, lpcbData);
    }

    LSTATUS Init(HKEY hKey, PCWSTR lpSubKey)
    {
        return RegCreateKeyExW(hKey, lpSubKey, 0, 0, 0, KEY_ALL_ACCESS, 0, &_hKey, 0);
    }
};

//void test_cfg()
//{
//    CConfig cfg;
//    if (!cfg.Init(HKEY_CURRENT_USER, L"Software\\MyKey"))
//    {
//        struct winpos_t
//        {
//            DWORD dwWindowStyle;
//            int iWindowX;
//            int iWindowY;
//        };
//
//        winpos_t test_pos = { 1, 2, 3 };
//
//        static const PCWSTR szwinpos_t = L"winpos_t";
//
//        if (!cfg.Save(szwinpos_t, REG_BINARY, &test_pos, sizeof(test_pos)))
//        {
//            ULONG type, cb = sizeof(test_pos);
//            RtlZeroMemory(&test_pos, sizeof(test_pos));
//            if (!cfg.Load(szwinpos_t, &type, &test_pos, &cb) && type == REG_BINARY && cb == sizeof(test_pos))
//            {
//                printf("{%x, %x, %x}\n", test_pos.dwWindowStyle, test_pos.iWindowX, test_pos.iWindowY);
//            }
//        }
//    }
//}

c++ - Saving settings to Windows registry as a tuple - Code Review Stack Exchange