代碼
LONG lRegRet;
HLOCAL hLocal;
HKEY hKeyUser;
PTSTR pszEnvironmentName = NULL;
PTSTR pszEnvironmentValue = NULL;
pszEnvironmentName = (PTSTR)malloc(MAX_PATH * sizeof(TCHAR));
GetDlgItemText(hDlg, IDD_EDIT_NAME, pszEnvironmentName, MAX_PATH);
pszEnvironmentValue = (PTSTR)malloc(1024 * sizeof(TCHAR) * 3);
GetDlgItemText(hDlg, IDD_EDIT_VALUE, pszEnvironmentValue,
1024 * sizeof(TCHAR) * 3);
//修改用戶環境變量
lRegRet = RegOpenKeyEx(HKEY_CURRENT_USER, USER_ENVREG, KEY_ALL_ACCESS, 0, &hKeyUser);
if (lRegRet != ERROR_SUCCESS)
{
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, NULL, lRegRet,
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), (PTSTR)&hLocal, 0, NULL);
MessageBox(hDlg, (PCTSTR)LocalLock(hLocal), TEXT("錯誤"), MB_OK);
break;
}
RegSetValueEx(hKeyUser, pszEnvironmentName, 0, REG_SZ,
(const unsigned char *)pszEnvironmentValue,
wcslen(pszEnvironmentValue) + sizeof(TCHAR));
RegCloseKey(hKeyUser);
SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)TEXT("Environment"));
//釋放分配的內存
free(pszEnvironmentValue);
free(pszEnvironmentName);
找到原因了,RegOpenKeyEx函數的參數你寫倒了,第三位是ulOption保留,通常必須設置為0,第四位是samDesired用來設置對鍵訪問的權限,你剛好寫反了。
lRegRet = RegOpenKeyEx(HKEY_CURRENT_USER, USER_ENVREG, 0, KEY_ALL_ACCESS, &hKeyUser);