How to refresh an application to modify the system environment variables?

After the system environment variables to manually add new page path, after determining the system will automatically refresh the environment variables, but when we modify the program through the API, without some process, system or old environment, to find accessible via cmd is not to.

First, the system environment variable corresponding to the registry is HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ Session Manager \ Environment ( manager authority needed), after modification by RegSetValue other functions, such as increasing the path to the new path of the micro-channel, in this case performed in CMD WeChat is invalid and must be restarted to take effect, or enter the following interface, then click OK after take effect.
Here Insert Picture Description
The solution is to use SendMessageTimeout function broadcasts a message.
SendMessageTimeout very simple: parameters are as follows:

hWnd:接收消息的窗口的句柄。如果为HWND_BROADCAST,则消息会被发送到系统中所有顶层窗口,包括无效或不可见的窗口。
Msg:指定被发送的消息。
wParam:指定附加的信息。
IParam:指定附加的信息。
fuFlags:指定如何发送消息。此参数可为下列值的组合:
SMTO_ABORTIFHUNG:如果接收线程没有响应或挂起,则函数将返回,而无需等待超时时间过去。
SMTO_BLOCK:阻止调用线程处理其他任何请求,直到函数返回为止。
SMTO_NORMAL:在等待函数返回时,不会阻止调用线程处理其他请求。
SMTO_NOTIMEOUTIFNOTHUNG:只要接收线程正在处理消息,该函数就不会强制执行超时期限。
SMTO_ERRORONEXIT:如果在处理消息时接收窗口被破坏或它自己的线程死亡,则该函数应返回0。
uTimeout:超时时间,当最多15秒的时间.
lpdwResult消息处理的结果。

根据上面参数,首先hWnd要设置为HWND_BROADCAST,Msg为WM_SETTINGCHANGE,MSDN对WM_SETTINGCHANGE的解释是,更改系统或用户的环境变量,要将lParam设置为字符串"Environment",wParam可以为0,详细可以查看https://docs.microsoft.com/en-us/windows/win32/winmsg/wm-settingchange页面。

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern long SendMessageTimeout(IntPtr windowHandle, uint Msg,IntPtr wParam, string lParam, uint flags, uint timeout, out long result);

public static void RefreshEnvironment() {
      long result;
      SendMessageTimeout(new IntPtr(HWND_BROADCAST), WM_SETTINGCHANGE, IntPtr.Zero,
          "Environment", SMTO_ABORTIFHUNG, 5000, out result);
}
Published 42 original articles · won praise 7 · views 7711

Guess you like

Origin blog.csdn.net/HouXinLin_CSDN/article/details/104544414