2

我正在尝试设置系统环境变量,我注意到要反映的更改我必须执行 SendMessageTimeout 来更新窗口。

我可以让它运行,并返回 0 结果,但环境变量实际上并没有更新。

[Flags]
public enum SendMessageTimeoutFlags : uint
{
    SMTO_NORMAL = 0x0,
    SMTO_BLOCK = 0x1,
    SMTO_ABORTIFHUNG = 0x2,
    SMTO_NOTIMEOUTIFNOTHUNG = 0x8
}

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
IntPtr hWnd,
uint Msg,
UIntPtr wParam,
IntPtr lParam,
SendMessageTimeoutFlags fuFlags,
uint uTimeout,
out UIntPtr lpdwResult);


string reg_subkey = "Test1";
string reg_name = @"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment";
Registry.SetValue(reg_name, reg_subkey, "testing", RegistryValueKind.String);

IntPtr HWND_BROADCAST = new IntPtr(0xffff);
const uint WM_WININICHANGE = 0x001A;
const uint WM_SETTINGCHANGE = WM_WININICHANGE;
const int MSG_TIMEOUT = 15000;
UIntPtr RESULT;

string ENVIRONMENT = "Environment";

SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, UIntPtr.Zero, (IntPtr)Marshal.StringToHGlobalAnsi(ENVIRONMENT), SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, MSG_TIMEOUT, out RESULT);
4

2 回答 2

4

最简单的方法是使用Environment.SetEnvironmentVariable. 这在内部调用SendMessageTimeout

于 2014-06-17T11:09:01.177 回答
1

我会尝试使用Environment.SetEnvironmentVariable后面的函数SendMessageTimeout,这在我的团队测试中有效,在机器上下文中更新 PATH 变量。我们还发现Environment.SetEnvironmentVariable只有在创建新变量时才能单独工作的文档相反。我们在父进程必须获取更新的 PATH 变量的场景中进行测试。

于 2014-12-09T17:15:02.087 回答