runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

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

 

网上一般这样调用的

SendMessageTimeout(
                     new IntPtr(HWND_BROADCAST), 
                     WM_SETTINGCHANGE, 
                     IntPtr.Zero, 
                     IntPtr.Zero,
                     SendMessageTimeoutFlags.SMTO_NORMAL,
                     1000,
                     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, 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的小工具,可闹腾了些天。

posted on 2013-12-24 17:25  runliuv  阅读(4959)  评论(0编辑  收藏  举报