想在Windows下通过编程修改环境变量的值,并且希望修改完后立即生效。
一、环境变量的修改
(1)修改当前进程的某个环境变量:SetEnvironmentVariable。
(2)修改系统环境变量:在注册表HKEY_LOCAL_MACHINESystemCurrentCont
(3)修改用户环境变量:在注册表中HKEY_CURRENT_USEREnvironment修改。
二、环境变量的生效
在网上搜了一下,有两种说法:
(1)SendMessage(HWND_BROADCAST,WM_SETTINGCHANGE,0,(LPARAM)TEXT("Environment"));
(2)SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,LPARAM("Environment"), SMTO_ABORTIFHUNG, 5000, &MsgResult);
没有尝试,先记在这儿。
很简单:
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,LPARAM("Environment"), SMTO_ABORTIFHUNG, 5000, &MsgResult);
发一个全局的广播,等待各自相应后,立即生效。
{ Note: We originally used SendNotifyMessage to broadcast the message but it
turned out that while it worked fine on NT 4 and 2000 it didn't work on XP
-- the string "Environment" in lParam would be garbled on the receiving
end (why I'm not exactly sure). We now use SendMessageTimeout as directed
in the KB article 104011. It isn't as elegant since it could cause us to
be delayed if another app is hung, but it'll have to do. }