简体   繁体   中英

Is there a way to set the environment path programmatically in C++ on Windows?

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?

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.

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\

There is no API - changing the registry is the way to do it. The changed value will be used for processes starting after the change was made.

Also: Notice that running applications must actively process the settings changed message and many (most?) do not do so.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM