【发布时间】:2020-12-11 12:56:59
【问题描述】:
我想使用 c++ 将新路径附加到现有环境变量。这应该是针对当前用户的(如果您可以提供 Local_Machine 的示例,那也是可以接受的)。
路径(新)和变量(已经存在)是
variable = Cur
path = E:\Softwares\Setup
我尝试过的
void SetUserVariablePath(){
HKEY hkey;
long regOpenResult;
const char key_name[] = "Environment";
const char path[]="E:\\Softwares\\Setup;"; //new path
LPCSTR stuff = "Cur"; //Variable Name
// here we open the variable and set the value
regOpenResult = RegOpenKeyEx(HKEY_CURRENT_USER,key_name, 0, KEY_ALL_ACCESS, &hkey);
RegSetValueEx(hkey,stuff,0,REG_EXPAND_SZ,(BYTE*) path, strlen(path)+1);
// tell other process to update their env values
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_BLOCK, 100, NULL);
// close the registery key
RegCloseKey(hkey);
}
我已经关注how-to-add-environment-variable-in-c 上面的代码。代码确实有效并为当前用户设置了环境变量,但它也覆盖了已经存在的任何现有路径,我想要做什么是追加到现有路径。
无法回答我的问题的事情
- 我不打算为当前/子进程设置变量(可以使用 setenv() 或 _putenv() 函数完成)。
- 我已经查看了这些问题,但它们没有回答我的问题。 Update system environment variable from c++ 和 Set system variable from C++
【问题讨论】:
-
显然您需要做的是 1) 使用
RegGetValue获取现有路径,2) 将路径附加到您从步骤 1 获得的路径,3) 使用RegSetValueEx保存组合路径.看起来很简单。您是否尝试过类似的方法但没有成功?如果是这样,您应该发布您尝试过的代码。
标签: c++ environment-variables registry system-paths