I am trying to change Windows 7 proxy settings using .NET. I have verified by refreshing the key itself via F5 in the registry editor that the code below successfully sets the keys, but Windows doesn't appear to acknowledge the changes when I open Internet Settings via Control Panel.
However, when I make the changes manually through Control Panel, the settings take immediately.
This tells me that the Control Panel UI is somehow telling Windows to reload the key values whereas doing it directly via .NET code just sets the values without being reloaded.
Is there a command I can issue to Windows via .NET code to force it to reload any registry changes?
using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.Users, RegistryView.Registry64))
using (var myKey = hklm.OpenSubKey(@"[..]\Software\Microsoft\Windows\CurrentVersion\Internet Settings", true))
{
if (myKey != null)
{
myKey.SetValue("ProxyServer", "00.00.00.00:0000", RegistryValueKind.String);
myKey.SetValue("ProxyEnable", 1, RegistryValueKind.DWord);
}
}
Update: I just discovered that reopening Internet Properties via Control Panel forces a refresh. While this isn't a tenable solution, it does confirm that some command is being issued to Windows to tell it to reload registry changes.
So, in asking my question, I gave myself more search criteria ideas which eventually led me to this post where someone was trying to do the exact same thing as I am right now:
It's Powershell, but I converted it to c#. After calling InternetSetOption
, the changes are reflected immediately.
[DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
const int INTERNET_OPTION_REFRESH = 37;
using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.Users, RegistryView.Registry64))
using (var myKey = hklm.OpenSubKey(@"[..]\Software\Microsoft\Windows\CurrentVersion\Internet Settings", true))
{
if (myKey != null)
{
myKey.SetValue("ProxyServer", "00.00.00.00:0000", RegistryValueKind.String);
myKey.SetValue("ProxyEnable", 1, RegistryValueKind.DWord);
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
}
}