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 Main.cs (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);
            }
        }
    }
}

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 prefs.js 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.