How to add environment variable in C ++?

Is it possible to add an environment variable in Windows via C ++?

They need to be added to "My Computer-> Properties-> Advanced Environment Variables"

thanks

+4
source share
5 answers

from MSDN :

To programmatically add or change system variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast the WM_SETTINGCHANGE message with lParam set to the "Environment" line. This allows applications like the shell to pick up their updates ...

+10
source

The only way I know is through the registry.

Hint: global variables are located in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment and for each user in HKEY_USERS\*\Environment , where * denotes the SID of the user.

Good luck.

+3
source

Here's a simple implementation (based on the MSDN instruction sent by SteelBytes):

 bool SetPermanentEnvironmentVariable(LPCTSTR value, LPCTSTR data) { HKEY hKey; LPCTSTR keyPath = TEXT("System\\CurrentControlSet\\Control\\Session Manager\\Environment"); LSTATUS lOpenStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyPath, 0, KEY_ALL_ACCESS, &hKey); if (lOpenStatus == ERROR_SUCCESS) { LSTATUS lSetStatus = RegSetValueEx(hKey, value, 0, REG_SZ,(LPBYTE)data, strlen(data) + 1); RegCloseKey(hKey); if (lSetStatus == ERROR_SUCCESS) { SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_BLOCK, 100, NULL); return true; } } return false; } 
0
source

Windows environment variables are stored in the Windows registry. You can use the "SetEnvironmentVariable" function for this purpose, see the function documentation at the link below.

http://msdn.microsoft.com/en-us/library/96xafkes.aspx

-1
source

Source: https://habr.com/ru/post/1342997/


All Articles