How to add environment variable in C++?

11,474

Solution 1

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 a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates ...

Solution 2

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.

Solution 3

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;
}
Share:
11,474
VextoR
Author by

VextoR

Updated on July 08, 2022

Comments

  • VextoR
    VextoR almost 2 years

    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