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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Joe HM

    #1

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

    Hello -

    I am putting together a little ConsoleApplicat ion 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 SendMessageTime out Lib "user32" Alias
    "SendMessageTim eoutA" (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_ABORTIFHUN G As Long = &H2

    Sub SetSystemEnviro nmentVariable(B yVal EnvName As String, ByVal
    EnvValue As String)
    Dim resApi As Long
    Dim regVersion As RegistryKey
    Dim subkey As String

    subkey = "SYSTEM\Current ControlSet\Cont rol\Session Manager
    \Environment"

    regVersion = Registry.LocalM achine.OpenSubK ey(subkey, True)

    regVersion.SetV alue(EnvName, EnvValue)
    regVersion.Clos e()

    SendMessageTime out(HWND_BROADC AST, _
    WM_WININICHANGE , _
    0, _
    "Environmen t", _
    SMTO_ABORTIFHUN G, _
    5000, _
    resApi)
    End Sub

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

    Thanks,
    Joe

Working...