I need to set an environment variable programmatically.
Microsoft provides documentation for that here. You just need to create a new value in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
. This part works fine.
The problem is that these changes only come into effect after logging out and logging in again.
To circument this they propose to execute this little piece of code:
if (!SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
(LPARAM) "Environment", SMTO_ABORTIFHUNG,
5000, &dwReturnValue))
{
... take action in case of failure
}
I did exactly this, SendMessageTimeout
returns TRUE
, but at least under Windows 10 it has no effect. A newly opened command prompt window still won't show the newly created variable.
I also tried to run this piece of code in an elevated process, but the result is still the same.
But when I use system applet for changing environment variables, my newly created variable shows up and when I click OK on the applet and when I open another command prompt, then the variable is there.
Any thoughts?