// 返回 ERROR_FILE_NOT_FOUND 表示沒有,返回 ERROR_SUCCESS 表示成功
static LONG OpenKey(HKEY hRootKey, wchar_t* strKey, HKEY &hKey)
{
LONG nError = RegOpenKeyEx(hRootKey, strKey, NULL, KEY_ALL_ACCESS, &hKey);
return nError;
}
// 創建之後已經打開,直接使用 hKey
static bool CreateKey(HKEY hRootKey, wchar_t* strKey, HKEY& hKey)
{
LONG nError = RegCreateKeyEx(hRootKey, strKey, NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL);
if (nError == ERROR_SUCCESS)
{
return true;
}
return false;
}
static bool SetVal(HKEY hKey, LPCTSTR lpValue, DWORD data)
{
LONG nError = RegSetValueEx(hKey, lpValue, NULL, REG_DWORD, (LPBYTE)& data, sizeof(DWORD));
if (nError == ERROR_SUCCESS)
return true;
return false;
}
// 返回 ERROR_FILE_NOT_FOUND 表示沒有,返回 ERROR_SUCCESS 表示成功
static LONG GetVal(HKEY hKey, LPCTSTR lpValue, DWORD &data)
{
DWORD size = sizeof(data);
DWORD type = REG_DWORD;
LONG nError = RegQueryValueEx(hKey, lpValue, NULL, &type, (LPBYTE)& data, &size);
return nError;
}
static void CloseKey(HKEY &hKey)
{
RegCloseKey(hKey);
}
使用
HKEY hRetKeyTmp;
LPCWSTR tmp= L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\tmp";
LONG lRet = OpenKey(HKEY_LOCAL_MACHINE, (wchar_t *)tmp, hRetKeyTmp);
if (lRet == ERROR_FILE_NOT_FOUND)
{
width = 1024;
if (CreateKey(HKEY_LOCAL_MACHINE, (wchar_t*)tmp, hRetKeyTmp))
{
SetVal(hRetKeyTmp, L"Width", width);
}
}