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
读写字符串类型:
void init() { CConfig cfg; static const PCWSTR keyName = L"myKey"; if (cfg.Init(HKEY_CURRENT_USER, L"Software\\zhiyiUpdater")) return; string content("init"); ULONG type; DWORD cb = content.length()+1; if (cfg.Save(keyName, REG_SZ, content.c_str(), cb)) { OutputDebugPrintf("save data failed"); } char buffer[100]; DWORD size = sizeof(buffer); if (cfg.Load(keyName, &type, &buffer, &size)) {
OutputDebugPrintf("read data failed");
}
free(buffer);
}
//封装 存储字符串 class localStorage { public: string getItem(string key); bool setItem(string key, string val); }; string localStorage::getItem(string key) { CConfig cfg; const PCWSTR keyName = charToWchar(key.c_str()); if (cfg.Init(HKEY_CURRENT_USER, L"Software\\zhiyiUpdater")) return NULL; ULONG type; WCHAR buffer[100]; DWORD size = sizeof(buffer); if (cfg.Load(keyName, &type, &buffer, &size)) { string err("err"); return err; } string res(wstr2str(buffer)); return res; } bool localStorage::setItem(string key, string val) { CConfig cfg; if (cfg.Init(HKEY_CURRENT_USER, L"Software\\zhiyiUpdater")) return false; TCHAR buffer[100]; DWORD size = sizeof(buffer); const PCWSTR keyName = charToWchar(key.c_str()); const PCWSTR value = charToWchar(val.c_str()); return cfg.Save(keyName, REG_BINARY, value, sizeof(wchar_t) * (val.length() + 1)); }