Wednesday, December 27, 2006

Windows environment variables

Windows has two kinds of environment variables
1) User specific environment variables
2) System wide environment variables

User specific environment variables are available only to the user for which it is created and System wide are available to all the users.

These environment variables are stored in the following registry location

You can modify user environment variables by editing the following Registry key: HKEY_CURRENT_USER \Environment

You can modify system environment variables by editing the following Registry key: HKEY_LOCAL_MACHINE \SYSTEM \CurrentControlSet \Control \Session Manager \Environment

Note: If you modify the environment variables it won't reflect immediately till you log-off and log-in again.

Changes to environment variable

To effect the changes to the environment variable immediately without log off, broadcast the WM_SETTINGCHANGE message to all windows in the system, so the system will will peform read from registry again to update the environment variable.

C# code to propagate environment variable changes

/* Declare the Win32 API for propagating the environment variable */
[DllImport("user32.dll",CharSet=CharSet.Auto, SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)]
public static extern bool SendMessageTimeout(
IntPtr hWnd,
int Msg,
int wParam,
string lParam,
int fuFlags,
int uTimeout,
int lpdwResult
/* Constant to broadcast message to all windows */
public const int HWND_BROADCAST = 0xffff;
public const int WM_SETTINGCHANGE = 0x001A;
public const int SMTO_NORMAL = 0x0000;
public const int SMTO_BLOCK = 0x0001;
public const int SMTO_ABORTIFHUNG = 0x0002;
public const int SMTO_NOTIMEOUTIFNOTHUNG = 0x0008;

/* Call the API passing the last parameter as out parameter */
int result,retun_value;
return_value = SendMessageTimeout( (System.IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment",SMTO_BLOCKSMTO_ABORTIFHUNG SMTO_NOTIMEOUTIFNOTHUNG, SomeTimeoutValue, out result);

MessageBox.Show(" Broadcast to all window successfull! ");
MessageBox.Show(" Broadcast to all window failed! ");

For more information check out the following links


Post a Comment

<< Home