By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,793 Members | 1,252 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,793 IT Pros & Developers. It's quick & easy.

How to create a System Environment Variable and update it in current cmd.exe?

P: n/a
Hello -

I am putting together a little ConsoleApplication that is supposed to
check for an Environment Variable and create it if it does not exist.
I found some code that will add a new Environment Variable to the
Registry and send a broadcast message to all open windows to update
their environment.

When I run this *.exe out of a cmd.exe, it will not update the
environment of that shell. The new Environment Variable shows up
under My Computer Properties Advanced Environment Variables but
the rest of the system does not seem to know about it. I guess if I
restart my computer it would work.

Here is the code ...

Public Declare Function SendMessageTimeout Lib "user32" Alias
"SendMessageTimeoutA" (ByVal hWnd As Long, _

ByVal Msg As Long, _

ByVal wParam As Long, _

ByVal lParam As String, _

ByVal fuFlags As Long, _

ByVal uTimeout As Long, _

ByVal lpdwResult As Long) As Long

Public Const HWND_BROADCAST As Long = &HFFFF&
Public Const WM_WININICHANGE As Long = &H1A
Public Const SMTO_ABORTIFHUNG As Long = &H2

Sub SetSystemEnvironmentVariable(ByVal EnvName As String, ByVal
EnvValue As String)
Dim resApi As Long
Dim regVersion As RegistryKey
Dim subkey As String

subkey = "SYSTEM\CurrentControlSet\Control\Session Manager
\Environment"

regVersion = Registry.LocalMachine.OpenSubKey(subkey, True)

regVersion.SetValue(EnvName, EnvValue)
regVersion.Close()

SendMessageTimeout(HWND_BROADCAST, _
WM_WININICHANGE, _
0, _
"Environment", _
SMTO_ABORTIFHUNG, _
5000, _
resApi)
End Sub

Has anyone ever done something similar and got it to work?

Thanks,
Joe

Mar 1 '07 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.