I work in a school and i am currently working on a program which can switch the proxy settings on-the-fly in Windows Vista and Windows 7.

So far my code works fine if the browser is restarted but it doesn't on-the-fly. The settings will change once without a restart but then they wont take any effect at all. Would greatly appreciate any help at all. Here is the code from (That matters anyway i've tried to keep it sweet)

Many Thanks in advance.

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace ProxySwitch
{
    public partial class Main : Form
    {
        [DllImport("wininet.dll")]
        public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
        public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
        public const int INTERNET_OPTION_REFRESH = 37;

        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
                Hide();
        }

        private void ProxyOnMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists("Config.prsw"))
                {
                    string ProxyAddress;

                    System.IO.StreamReader ConfigFile =
                        new System.IO.StreamReader("Config.prsw");
                    while ((ProxyAddress = ConfigFile.ReadLine()) != null)
                    {
                        RegistryKey InternetSettings = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                        InternetSettings.SetValue("ProxyEnable", 1);
                        InternetSettings.SetValue("ProxyServer", (ProxyAddress));

                        InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
                        InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
                    }
                    ConfigFile.Close();

                    MessageBox.Show("The proxy settings have now been turned on!", "Successful!",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    MessageBox.Show("The configuration file could not be found! Please contact the system administrator", "Oh noes!",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch(System.Exception ErrorCode)
            {
                MessageBox.Show(ErrorCode.Message, "Oh noes!",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ProxyOffMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (File.Exists("Config.prsw"))
                {
                    string ProxyAddress;

                    System.IO.StreamReader ConfigFile =
                        new System.IO.StreamReader("Config.prsw");
                    while ((ProxyAddress = ConfigFile.ReadLine()) != null)
                    {
                        RegistryKey InternetSettings = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                        InternetSettings.SetValue("ProxyEnable", 0);
                        InternetSettings.SetValue("ProxyServer", "");

                        InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
                        InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
                    }
                    ConfigFile.Close();

                    MessageBox.Show("The proxy settings have now been turned off!", "Successful!",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    MessageBox.Show("The configuration file could not be found! Please contact the system administrator", "Oh noes!",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (System.Exception ErrorCode)
            {
                MessageBox.Show(ErrorCode.Message, "Oh noes!",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

Dani AI

Generated

Short diagnosis and a practical plan based on the thread: editing the HKCU Internet Settings key sometimes appears to work (as found) but many browser processes cache WinINet settings per-process, so a registry write alone is fragile. Toggling ProxyEnable (as suggested) or killing IE (as resorted to) are hacks that explain the behavior you see, but there are more reliable, supported approaches. Setting and retrieving Internet options with WinINet is the authoritative reference.

Use the WinINet API to set connection-level proxy data (INTERNET_PER_CONN_OPTION_LIST / INTERNET_PER_CONN_OPTION) rather than only poking registry values, then notify the system. After setting per-connection options, call the Win32 notification path (InternetSetOption for the settings-changed/refresh semantics and broadcast a WM_SETTINGCHANGE) so top-level windows are told to reload relevant settings. See the WinINet reference for the per-connection option approach. INTERNET_PER_CONN_OPTION documentation and the WM_SETTINGCHANGE guidance are helpful. WM_SETTINGCHANGE (SendMessageTimeout)

A few practical notes grounded in the posts here:

  • WinINet is a desktop API (not for services); if this runs in a service, use WinHTTP instead. WinINet docs note this limitation.
  • Firefox rewrites prefs files while running; editing prefs.js directly is fragile — use user.js / autoconfig or restart Firefox after changes. (Mozilla docs warn against editing prefs.js while Firefox runs.)
  • Some Chromium/third‑party processes still won’t pick up changes reliably; there is no guaranteed way to force every process to reload proxy state without restarting it (see practical reports).

If a seamless, no-restart workflow is required, consider using a PAC/WPAD setup and flip the PAC logic (or PAC URL) so clients perform an in-process decision instead of changing system registry keys. Proxy Auto-Config (PAC) guide

Example: broadcast a setting-change after updating options (C# P/Invoke for SendMessageTimeout shown as a minimal helper):

[DllImport("user32.dll", SetLastError=true)]
static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
const int HWND_BROADCAST = 0xffff;
const uint WM_SETTINGCHANGE = 0x001A;
UIntPtr result;
SendMessageTimeout((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, UIntPtr.Zero, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", 0, 1000, out result);

Checklist: set per-connection options, notify WinINet and broadcast WM_SETTINGCHANGE, prefer PAC for runtime switching, and only restart the specific browser process as a last resort.

Use this instead

void SetProxy(string strProxy)
        {
            RegistryKey RegKey = Registry.CurrentUser.OpenSubKey
            (@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            RegKey.SetValue("ProxyServer", strProxy);
            RegKey.SetValue("ProxyEnable", 1);
            RegKey.SetValue("ProxyEnable", 0);
        }

Thanks for the reply but no cigar.

I have managed to do it via a hacky way using this:

InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
                        InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
                    }
                    ConfigFile.Close();

                    MessageBox.Show("The proxy settings have now been turned off!", "Successful!",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    System.Windows.Forms.Application.Restart();
                }

Not the best idea though if anyone has any better?

Hi

i found that calling InternetSetOption as you have shown above just ensures the registry settings get reset on Win 7 running IE6 and the only way i've found that works is to kill the IExplore process which is not perfect.

I also managed to get FireFox to use the new settings buy editing the for the current user but again i have to kill the process.

Will post the code below if it's any help.

public class SetProxySettings
    {
        [DllImport("wininet.dll")]
        public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
        public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
        public const int INTERNET_OPTION_REFRESH = 37;
        bool settingsReturn, refreshReturn;
        public void SwitchProxy(int Port, bool Enable, string IPAddress, bool AutoKillIE, bool AutoKillFireFox)
        {
            if (AutoKillIE)
                Proxy.ProxyHelper.KillProcess("iexplore");
            if (AutoKillFireFox)
                Proxy.ProxyHelper.KillProcess("FireFox");
            RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
            if (Enable)
                registry.SetValue("ProxyEnable", 1);
            else
                registry.SetValue("ProxyEnable", 0);
            registry.SetValue("ProxyServer", "127.0.0.1:" + Port);
            //###### IMPORTANT i tried using API call other have said to use but the enable flag in the registry keeps getting reset ###################
            //###### Un-comment the lines below to make the API Call                                                                 ###################
            //settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
            //refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
            //That should had switched IE so lets do Firefox if we can find the prefs.js File for this users
            SwitchFireFox(Port, Enable, IPAddress);
        }

        private void SwitchFireFox(int Port, bool Enable, string IPAddress)
        {//This function looks for Firefoxes prefs.js file for the current user
            string RootPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal).ToLower().Replace("documents", "") + "AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\";
            DirectoryInfo RootInfo = new DirectoryInfo(RootPath);
            foreach (DirectoryInfo DInfo in RootInfo.GetDirectories())
            {
                foreach (FileInfo FInfo in DInfo.GetFiles())
                {
                    if (FInfo.Name.ToLower() == "prefs.js")
                    {
                        EditPrefsJS(FInfo, Port, Enable, IPAddress);
                    }
                }
            }
        }

        private void EditPrefsJS(FileInfo FInfo, int Port, bool Enable, string IPAddress)
        {//This function edits firefoxes prefs.js file to turn the proxy server on/off
            bool HasIP = false;
            bool HasPort = false;
            bool HasEnabled = false;
            string NewData = "";
            System.IO.FileStream FS = FInfo.OpenRead();
            byte[] Data = new byte[FS.Length];
            if (Data.Length > FS.Length)
                Data = new byte[FS.Length];
            FS.Read(Data, 0, Data.Length);
            FS.Close();
            string FileData = ASCIIEncoding.ASCII.GetString(Data).Replace(Environment.NewLine, "¬");
            string[] Lines = FileData.Split('¬'); ;
            foreach (string Line in Lines)
            {
                string LineOutput = Line;
                if (Line.ToLower().IndexOf("user_pref(\"network.proxy.") > -1)
                {
                    if (Line.ToLower().IndexOf(".http\"") > -1)
                    {
                        HasIP = true;
                        NewData += "user_pref(\"network.proxy.http\", \"" + IPAddress + "\");" + Environment.NewLine;
                    }
                    if (Line.ToLower().IndexOf("http_port") > -1)
                    {
                        HasPort = true;
                        NewData += "user_pref(\"network.proxy.http_port\"," + Port + ");" + Environment.NewLine;
                    }
                    if (Line.ToLower().IndexOf("proxy.type") > -1 && Enable)
                    {
                        HasEnabled = true;
                        NewData += "user_pref(\"network.proxy.type\", 1);" + Environment.NewLine;
                    }
                    if (Line.ToLower().IndexOf("proxy.type") > -1 && !Enable)
                    {
                        HasEnabled = true;
                        NewData += "user_pref(\"network.proxy.type\", 0);" + Environment.NewLine;
                    }
                }
                else
                    NewData += Line + Environment.NewLine;
            }
            //If the prefs.js file did not contain the correct user_pref then add them to the end of the file
            if (!HasIP)
                NewData += "user_pref(\"network.proxy.http\", \"" + IPAddress + "\");" + Environment.NewLine;
            if (!HasPort)
                NewData += "user_pref(\"network.proxy.http_port\"," + Port + ");" + Environment.NewLine;
            if (!HasEnabled)
            {
                if (Enable)
                    NewData += "user_pref(\"network.proxy.type\", 1);" + Environment.NewLine;
                else
                    NewData += "user_pref(\"network.proxy.type\", 0);" + Environment.NewLine;
            }
            Proxy.ProxyHelper.SaveFile(FInfo.FullName, NewData, true);//Calls function to simply save the new file
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.