0

I need to set a local environment variable for current user and it shoukd be visible to other processes like a new command prompt. I need it for windows. I have tried options like putenv and editing the registry from C++ code but the new cmd prompt see the old values. Primarily i need to edit PATH variable along with few custom env variables. Will appreciate if i can get a working sample code.

Please note that the environment variable need to persist past program execution.

My requirement is for windows. I even tried running setx from C++ code and it works fine but for PATH variable it trims it down to 1024 character and i lose the update. Is there a workaround to this?

IF my wording looks confusing about the requirement. I need exactly same behavior as if i am using setx. Thanks in advance.

user888270
  • 613
  • 2
  • 8
  • 16
  • I would make an educated guess that you have correctly set things in registry but you are running into x64-32 virtualization. Is your cmd window of the same bitness as your application? – Sergei Vorobiev Mar 27 '17 at 00:07

2 Answers2

3

If you start Cmd.exe from your process you can control its environment. The environment variables are inherited from the parent process. They can also be overridden when you call CreateProcess.

If you change the users/system environment configuration in the registry(HKCU\Environment/HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment) and log off/reboot then the first process will use these new defaults.

If you update the registry you can tell other applications to refresh their environments without logging off by broadcasting a message:

BroadcastSystemMessage(0, 0, WM_SETTINGCHANGE, 0, (LPARAM)TEXT("Environment")); 

In reality it is only Explorer.exe that reacts to this message but that is enough to affect new applications started from the taskbar/start menu.

Anders
  • 97,548
  • 12
  • 110
  • 164
  • BroadcastSystemMessage always hang and if I set flag to no hang, it will return 0. – zzy Dec 19 '17 at 07:21
1

The setx command is actually an executable that sets values in the registry. If you are looking to simulate the behavior where you can set an environment variable that will last longer than the current process you will need to write it to the HKCU\Environment key. The HKCU is for the the current user and can be written to without elevated permissions.

Use RegEdit.exe or reg.exe query HKCU\Environment to view the current settings. From C/C++ you can use the Registry functions. If you can, I recommend using the ATL CRegKey class as it follows RAII and ensures handles are properly cleaned up.

linuxuser27
  • 7,183
  • 1
  • 26
  • 22