Is there a way to set the environment path programmatically in C++ on Windows?
Solution 1
MSDN Says:
Calling SetEnvironmentVariable has no effect on the system environment variables. To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates. Note that the values of the environment variables listed in this key are limited to 1024 characters.
Solution 2
As was pointed out earlier, to change the PATH at the machine level just change this registry entry:
HLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
But you can also set the PATH at the user level by changing this registry entry:
HKEY_CURRENT_USER\Environment\Path
And you can also set the PATH at the application level by adding the application\Path details to this registry entry:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
Solution 3
If you want to do it through the registry, you might want to look at the source code of this program.
Microsoft also provides a small command line utility called setx with its resource toolkits, which will let you do this. By the way, the regular set command just lets you define local environment variables I think.
Solution 4
Yes You are correct. You also need to effect these settings without logging off
Send Message of borad casting to all windows SETTINGCHANGE for the parameter (LPARAM) "Environment" with SMTO_ABORTIFHUNG for some milliseconds(5000) using SendMessageTimeout API.
This is what setX.exe provided with resource Kit does.
Related videos on Youtube
LK.
Updated on April 17, 2022Comments
-
LK. about 2 years
Is there a way to set the global windows path environment variable programmatically (C++)?
As far as I can see, putenv sets it only for the current application.
Changing directly in the registry(HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment)
is also an option though I would prefer API methods if there are?