c# .net 编程方式修改环境变量无效的解决办法

无论是修改注册表方式(System\ControlSet001\Control\Session Manager\Environment"),还是用Environment.SetEnvironmentVariable() 方法,其实最后只差一步。通知。

否则,只能重启操作系统生效。

网上一般这样调用的

SendMessageTimeout(
new IntPtr(HWND_BROADCAST),
WM_SETTINGCHANGE,
IntPtr.Zero,
IntPtr.Zero,
SendMessageTimeoutFlags.SMTO_NORMAL,
,
out result1);

超时不说,还无效。

在微软上搜索了一篇:http://social.msdn.microsoft.com/Forums/vstudio/zh-CN/2b9c995f-5ece-4cfd-83b2-fe84c96427a3/net-set-new-path-with-setenvironmentvariable?forum=netfxbcl

是这样调用的。

SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, "Environment", SMTO_ABORTIFHUNG, , 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,
,
out result1);
}
}
}

最后,正常生效了。

写个设置JDK、ANDROID SDK的小工具,可闹腾了些天。

上一篇:win7下iis的配置问题


下一篇:Android摘抄总结