我正在尝试设置系统环境变量,我注意到要反映的更改我必须执行 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);