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
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
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 ...
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;
}
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.
Have you tried Set local environment variables in C++?
The environment variables in Windows are stored in Windows Registry. You can use "System.Environment.SetEnvironmentVariable" .NET function for the purpose, please see the documentation of the function at link below.
#include <iostream>
#include <windows.h>
#include <cstring>
#include "tchar.h"
void SetUserVariablePath(){
HKEY hkey;
long regOpenResult;
const char key_name[] = "Environment";
const char path[]="D:/custom_command"; //new_value path need to update
regOpenResult = RegOpenKeyEx(HKEY_CURRENT_USER,key_name, 0, KEY_ALL_ACCESS, &hkey);
LPCSTR stuff = "VVS_LOGGING_PATH"; //Variable Name
RegSetValueEx(hkey,stuff,0,REG_SZ,(BYTE*) path, strlen(path));
RegCloseKey(hkey);
}
void GetUserVariablePath(){
static const char path[] = "VVS_LOGGING_PATH" ; //Variable Name
static BYTE buffer1[1000000] ;
DWORD buffsz1 = sizeof(buffer1) ;
{
//HKEY_CURRENT_USER\Environment
const char key_name[] = "Environment";
HKEY key ;
if( RegOpenKeyExA( HKEY_CURRENT_USER, key_name, 0, KEY_QUERY_VALUE, std::addressof(key) ) == 0 &&
RegQueryValueExA( key, path, nullptr, nullptr, buffer1, std::addressof(buffsz1) ) == 0 )
{
std::cout << "The updated value of the user variable is : " << reinterpret_cast<const char*>(buffer1) << '\n' ;
}
}
}
int main()
{
SetUserVariablePath();
GetUserVariablePath();
return 0;
}