简体   繁体   中英

Setting global environment variables programmatically

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?

The problem was solved by calling explicitly the wide version of SendMessageTimeout and sending the "Environment" as wide string:

SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 
                   (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 5000, &dwReturnValue);

As Michael found out, the string width needs to match the A/W function type. WM_SETTINGCHANGE is in the < WM_USER range and will be marshaled by the window manager.

You can use the TEXT macro to create code that works for everyone everywhere if you don't want to hardcode the function name suffix:

SendMessageTimeout(
  HWND_BROADCAST,
  WM_SETTINGCHANGE, 
  0, 
  (LPARAM) TEXT("Environment"),
  SMTO_ABORTIFHUNG,
  5000,
  &dwReturnValue
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM