
Help: SetEnvironmentVariable call don't work!
Quote:
>I cant get the SetEnvironmentVariable API call to work.
<cut>
You are not going nuts, just missing one important point: when VB starts it
reads the environment and loads it into memory and the Environ$ function is
reading this copy. Since VB does not support changing the variables there
is no way to refresh this cache and you will never see changes. In order to
read the "real" environment you must use the API as well. Try this:
Private Declare Function GetEnvironmentVariable Lib "kernel32" _
Alias "GetEnvironmentVariableA" (ByVal lpName As String, _
ByVal lpBuffer As String, ByVal nSize As Long) As Long
Private Declare Function SetEnvironmentVariable _
Lib "kernel32" Alias "SetEnvironmentVariableA" _
(ByVal lpName As String, ByVal lpValue As String) As Long
Private Sub Form_Load()
Dim lRet As Long
MsgBox "before: " & GetVariable("MYENV")
Randomize
lRet = SetEnvironmentVariable("MYENV", CStr(Rnd * 1000))
MsgBox "after: " & GetVariable("MYENV")
Unload Me
End Sub
Private Function GetVariable(ByVal VarName As String) As String
Dim sVal As String * 2048
Dim x As Long
x = GetEnvironmentVariable(VarName, sVal, Len(sVal) - 1)
If x > 0 Then
GetVariable = Left$(sVal, x)
Else
GetVariable = ""
End If
End Function
One other warning: the SHELL function apparently passes the original
environment so any changes you make will not be seen by anything you start
using Shell. You need to use the CreateProcess API call which lets you
pass a pointer to an environment block. Also, these changes will not affect
any processes outside your VB app and any children you create.