我正在尝试设置系统环境变量,我注意到要反映的更改我必须执行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);
答案 0 :(得分:4)
最简单的方法是使用Environment.SetEnvironmentVariable
。这会在内部调用SendMessageTimeout
。
答案 1 :(得分:1)
我会尝试使用Environment.SetEnvironmentVariable
函数,然后使用SendMessageTimeout
,这可以在我的团队测试中更新机器上下文中的PATH变量。我们还发现文档相反,Environment.SetEnvironmentVariable
在创建新变量时只能自行工作。我们正在测试父进程必须获取更新的PATH变量的场景。