使用C ++中的RegSetValueEx附加到用户环境变量

问题描述

我想使用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,KEY_ALL_ACCESS,&hkey);
    RegSetValueEx(hkey,stuff,REG_EXPAND_SZ,(BYTE*) path,strlen(path)+1);

    // tell other process to update their env values
    SendMessageTimeout(HWND_BROADCAST,WM_SETTINGCHANGE,(LPARAM)"Environment",SMTO_BLOCK,100,NULL); 
    
    // close the registery key
    RegCloseKey(hkey);
}

上面的代码我遵循了how-to-add-environment-variable-in-c。该代码确实有效并为当前用户设置了环境变量,但它也覆盖了所有已经存在的现有路径, 我想要的是要做的就是附加到现有路径上

无法回答我的问题

解决方法

我遵循了@john的建议,并得到了如下的工作代码

void appendReg()
{
    // commons
        static const char sysVar[] = "Cur" ;    // Variable Name 
        const char key_name[] = "Environment";  
        
        
    // first read the current value of registery    
        static BYTE curRegVal[1000000]; // will store the reg value
        DWORD curRegValCP = sizeof(curRegVal) ; 
        
        HKEY readKey;
        RegOpenKeyExA( HKEY_CURRENT_USER,key_name,KEY_QUERY_VALUE,&readKey);
        RegQueryValueExA( readKey,sysVar,nullptr,curRegVal,&curRegValCP);
        RegCloseKey(readKey);
        
        // curRegVal now has the current reg value
        std::cout<<"\nCurrent Reg value is = > "<< reinterpret_cast<const char*>(curRegVal);
    
    
    // second append the new path value to current value
        const char appendedVal[1000000]="C:\\New\\Dir\\To\\Be\\Appended;";  // to be appended
        strcat(appendedVal,curRegVal); // concatenate the current and new values
        std::cout<<"\nAppended Reg value is => "<<appendedVal;


    // third set the new(appended) value for registery and broadcast changes to other processes
        HKEY writeKey;
        RegOpenKeyEx(HKEY_CURRENT_USER,KEY_ALL_ACCESS,&writeKey); 
        RegSetValueEx(writeKey,(LPCSTR)sysVar,REG_EXPAND_SZ,(BYTE*) appendedVal,strlen(appendedVal)+1);  
        SendMessageTimeout(HWND_BROADCAST,WM_SETTINGCHANGE,(LPARAM)key_name,SMTO_BLOCK,100,NULL); // tell other process to update their env values
        RegCloseKey(writeKey);
}

这会将新路径附加到当前用户的环境变量中。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...