How to set an environment variable by setting it in the registry

By slightlybehindthecurve

It’s easy to do a “getenv” , but you’d be surprised at how hard it is to set an environment variable.
Sorry, I’m not going to take the time to write here what I learned from some excellent explanations found at codeguru and elsewhere, but I’ll try to post those links at the last.
Basically:
1) set the current user\environment\yourstring=value in the registry
2) send a windows refresh message (this doesn’t communicate with whatever command prompts you may already have, but it will work for the calling process)
3) whatever new command prompt or process will use your new setting


LRESULT CMainDlg::OnSetMyEnvironmentValue(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CString sNetId;
GetDlgItem(IDC_NETID).GetWindowTextA(sNetId);

Handle_SetReg(sNetId);
Handle_RefreshEnvironment();
return Handle_SetEnv(sNetId);
return 0;
}

int CMainDlg::Handle_SetEnv(CString sNetId)
{
//MessageBox (sNetId, "netid", 0) ; //sNetId.GetBuffer()

// set env variable
int iRet = 0;
iRet = SetEnvironmentVariable("netid", sNetId.GetBuffer() );

if( iRet <=0 )
{
GetLastError();
return -1;
}
return 0;

}

int CMainDlg::Handle_SetReg(CString sNetId)
{
CString subKey = "Environment";
HKEY hKey;
char *m_tmpChar = new char[100];

if (RegOpenKeyEx(HKEY_CURRENT_USER, subKey, 0, KEY_SET_VALUE, &hKey))
{
MessageBox("Error opening the key");
RegCreateKey(HKEY_CURRENT_USER, subKey,&hKey);
}

if ( RegSetValueEx(hKey, "netid" , NULL , REG_SZ, (unsigned char*)sNetId.GetBuffer() ,sNetId.GetLength() +1) )
MessageBox("Error setting the value");
RegCloseKey(hKey);

return 0;
}

// http://wiki.answers.com/Q/How_do_you_set_registry_entry_as_environment_variable
int CMainDlg::Handle_RefreshEnvironment()
{
DWORD_PTR dwReturnValue;

SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
(LPARAM) "Environment", SMTO_ABORTIFHUNG,
500, &dwReturnValue);
return dwReturnValue;
}

Here were some helpful links:
reading:
basics
http://www.codeguru.com/forum/showpost.php?p=1171365&postcount=7

REGISTRY
HKEY_CURRENT_USER\Environment
HKEY_CURRENT_USER\VolatileEnvironment
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
http://vlaurie.com/computers2/Articles/environment.htm
VISTA http://vistaonwindows.com/environment_variables.html

registry
http://www.codeguru.com/cpp/w-p/system/registry/print.php/c5793

6/4/09
helpful
http://wiki.answers.com/Q/How_do_you_set_registry_entry_as_environment_variable

looks like broadcasting the wm_settingchange won’t talk to cmd prompts
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2006-03/msg05284.html

Tags: ,

Leave a Reply