无论是修改注册表方式(SystemControlSet001ControlSession ManagerEnvironment"),还是用Environment.SetEnvironmentVariable() 方法,其实最后只差一步。通知。
否则,只能重启操作系统生效。
网上一般这样调用的
SendMessageTimeout( new IntPtr(HWND_BROADCAST), WM_SETTINGCHANGE, IntPtr.Zero, IntPtr.Zero, SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out result1);
超时不说,还无效。
是这样调用的。
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, "Environment", SMTO_ABORTIFHUNG, 100, IntPtr.Zero);
注意那个参数:"Environment"。
using System; using System.Runtime.InteropServices; namespace UsualLib { public class NotifyOS { // SendMessageTimeout tools [Flags] public enum SendMessageTimeoutFlags : uint { SMTO_NORMAL = 0x0000, SMTO_BLOCK = 0x0001, SMTO_ABORTIFHUNG = 0x0002, SMTO_NOTIMEOUTIFNOTHUNG = 0x0008 } const int WM_SETTINGCHANGE = 0x001A; const int HWND_BROADCAST = 0xffff; [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr SendMessageTimeout( IntPtr windowHandle, uint Msg, IntPtr wParam, string lParam, SendMessageTimeoutFlags flags, uint timeout, out IntPtr result ); public static void NotifyOS1() { IntPtr result1; //修改后发送一个消息给系统 //调用 SendMessageTimeout( new IntPtr(HWND_BROADCAST), WM_SETTINGCHANGE, IntPtr.Zero, "Environment", SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 200, out result1); } } }
最后,正常生效了。
写个设置JDK、ANDROID SDK的小工具,可闹腾了些天。