Is there any way I can add environment variable in Windows via C++?
They have to be added in "My computer->properties->advanced->environment variables"
Thank you
On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.
Standard environment variables are used for information about the user's home directory, terminal type, current locale, and so on; you can define additional variables for other purposes. The set of all environment variables that have values is collectively known as the environment.
The Global environment variables of your system are stored in /etc/environment . Any changes here will get reflected throughout the system and will affect all users of the system. Also, you need a Reboot, for any changes made here to take effect. User level Environment variables are mostly stored in .
2.2 Set/Unset/Change an Environment Variable for the "Current" CMD Session. To set (or change) a environment variable, use command " set varname=value ". There shall be no spaces before and after the '=' sign. To unset an environment variable, use " set varname= ", i.e., set it to an empty string.
from MSDN :
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 aWM_SETTINGCHANGE
message withlParam
set to the string "Environment". This allows applications, such as the shell, to pick up your updates ...
The only way I know is via the registry.
Hint, the global variables are in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
and those for each user in HKEY_USERS\*\Environment
, where *
denotes the SID of the user.
Good luck.
Here's a simple implementation (Based on the MSDN instruction posted 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With