Thursday, November 17, 2005

Set an environment variable using VB.NET

I found that there was no easy to use .net class to set an environment variable. So here is what I ended up with:
Imports System
Imports Microsoft.Win32
Imports System.Collections


Module Module1

    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 = &HFFFF&
    Public Const WM_WININICHANGE = &H1A
    Public Const SMTO_ABORTIFHUNG = &H2

    Sub SetUserEnvironmentVar(ByVal EnvName, ByVal EnvValue)
        Dim resApi As Long
        Dim regVersion As RegistryKey
        regVersion = Registry.CurrentUser.OpenSubKey("Environment", True)
        regVersion.SetValue(EnvName, EnvValue)
        regVersion.Close()
        SendMessageTimeout(HWND_BROADCAST, _
                            WM_WININICHANGE, _
                            0, _
                            "Environment", _
                            SMTO_ABORTIFHUNG, _
                            5000, _
                            resApi)
    End Sub

    Sub SetSystemEnvironmentVar(ByVal EnvName, ByVal EnvValue)
        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
    Sub Main()
        SetUserEnvironmentVar("USERVAR1", "Test Value")
        SetSystemEnvironmentVar("SYSTEMVAR1", "Test Value")
    End Sub

End Module

Some of the latest blog posts

Subscribe to RSS headline updates from:
Powered by FeedBurner