In this article, we will see about various registry functions and how we utilize it to create registry key , set and read its value.

Below is the implementation where we get open the registry, get the value and then set/update the value.

#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <iostream> HKEY OpenKey(HKEY hRootKey, wchar_t* stringKey) { HKEY hKey; //Registry Open Key Function LONG nError = RegOpenKeyEx(hRootKey, stringKey, NULL, KEY_ALL_ACCESS, &hKey); if (nError==ERROR_FILE_NOT_FOUND) { cout << "Create Registry key: " << stringKey << endl; nError = RegCreateKeyEx(hRootKey, stringKey, NULL, NULL, REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL, &hKey, NULL); } if (nError) cout << "Error: " << nError << " Could not find or create " << stringKey << endl; return hKey; } // Set the variable to some data void SetValue(HKEY hKey, LPCTSTR lpValue, DWORD data) { LONG nError = RegSetValueEx(hKey, lpValue, NULL, REG_DWORD, (LPBYTE)&data, sizeof(DWORD)); if (nError) cout << "Error: " << nError << " Could not set registry value: " << (char*)lpValue << endl; } DWORD GetValue(HKEY hKey, LPCTSTR lpValue) { DWORD data; DWORD size = sizeof(data); DWORD type = REG_DWORD; LONG nError = RegQueryValueEx(hKey, lpValue, NULL, &type, (LPBYTE)&data, &size); if (nError==ERROR_FILE_NOT_FOUND) data = 0; // The value will be created and set to data next time SetVal() is called. else if (nError) cout << "Error: " << nError << " Could not get registry value " << (char*)lpValue << endl; return data; } int main() { static DWORD val1, val2; HKEY hKey = OpenKey(HKEY_LOCAL_MACHINE,L"SOFTWARE\\MyPath"); val1 = GetValue(hKey, L"Value1"); val2 = GetValue(hKey, L"Value2"); val1 += 5; val2 += 2; SetValue(hKey, L"Value1", val1); SetValue(hKey, L"Value2", val2); RegCloseKey(hKey); return 0; }