C#广播环境变量更改通知bat脚本?

时间:2015-03-13 16:30:58

标签: c# windows batch-file cmd

我有一个修改环境变量的C#控制台应用程序

 RegistryKey key = Registry.CurrentUser.OpenSubKey("Environment", true);
 key.SetValue("BMKTARGET", targetLocation.Path, RegistryValueKind.String);

问题是在cmd中运行后,我必须关闭cmd并重新启动cmd以识别更改....因为cmd需要被告知它已被修改,所以我尝试运行这个代码我在网上找到:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SendMessageTimeout(
  IntPtr hWnd,
  int Msg,
  int wParam,
  string lParam,
  int fuFlags,
  int uTimeout,
  out int lpdwResult
);

public const int HWND_BROADCAST = 0xffff;
public const int WM_SETTINGCHANGE = 0x001A;
public const int SMTO_NORMAL = 0x0000;
public const int SMTO_BLOCK = 0x0001;
public const int SMTO_ABORTIFHUNG = 0x0002;
public const int SMTO_NOTIMEOUTIFNOTHUNG = 0x0008;
//Run this function after modification 
static void BroadcastEnvironment()
{
    int result;
    SendMessageTimeout((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment",
      SMTO_BLOCK | SMTO_ABORTIFHUNG | SMTO_NOTIMEOUTIFNOTHUNG, 5000, out result);
}

不知怎的,它仍然不起作用,我该如何解决这个问题呢?

注意:

我正在尝试将信息传递给运行此exe的.bat脚本...如果有更好的方法,我会对这个答案感到满意。

PS

评论中有人提出了一个看起来很好的建议,但没有足够的信息来测试它,如果有人可以详细说明,那将是值得赞赏的。

1 个答案:

答案 0 :(得分:1)

不需要所有那个注册表都在讨论。

Environment.SetEnvironmentVariable("BMKTARGET", targetLocation.Path,
                                   EnvironmentVariableTarget.User);

var value = Environment.GetEnvironmentVariable("BMKTARGET",
                                               EnvironmentVariableTarget.User)

此外,batch script@grawity上发布的此SuperUser可能会对您有所帮助。

@eryksun表示,您需要的不仅仅是脚本,而是批处理文件的单行代码:

for /f "tokens=2*" %%a in ('reg query HKCU\Environment /v BMKTARGET') do set "BMKTARGET=%%b"