Click here to Skip to main content
15,893,588 members
Articles / Programming Languages / C#
Article

Change Internet Explorer 7 Proxy Setting without Restarting Internet Explorer

Rate me:
Please Sign up or sign in to vote.
4.60/5 (11 votes)
4 Oct 2007CPOL 156.9K   3.6K   34   14
An article to explain how to change Internet Explorer 7 settings with Registy & WinINet API
TOR Activator Screenshoot

Introduction

This software shows how to change Proxy Settings in Internet Explorer 7 without restarting a new browser.

Background

This code uses WININET API to change InternetOptions and user32.dll to send a system message to inform Windows about the registry settings changes.

Using the Code

RegUtils.cs

This class modifies the Windows Registry settings.

C#
using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Win32;

namespace RedTomahawk.TORActivator
{
    internal class RegUtils
    {
        internal enum RegKeyType : int
        {
            CurrentUser = 1,
            LocalMachine = 2
        }

        internal RegUtils() { }

        // byte[]
        internal void GetKeyValue(RegKeyType KeyType, string RegKey,
            string Name, out byte[] Value)
        {
            RegistryKey oRegKey = null;

            switch ((int)KeyType)
            {
                case 1:
                    oRegKey = Registry.CurrentUser;
                    break;
                case 2:
                    oRegKey = Registry.LocalMachine;
                    break;
            }
            oRegKey = oRegKey.OpenSubKey(RegKey);

            Value = (byte[])oRegKey.GetValue(Name);

            oRegKey.Close();
        }

        // byte[]
        internal void SetKeyValue(RegKeyType KeyType, string RegKey,
            string Name, byte[] Value)
        {
            RegistryKey oRegKey = null;

            switch ((int)KeyType)
            {
                case 1:
                    oRegKey = Registry.CurrentUser;
                    break;
                case 2:
                    oRegKey = Registry.LocalMachine;
                    break;
            }

            oRegKey = oRegKey.OpenSubKey(RegKey, true);
            oRegKey.SetValue(Name, Value);
            oRegKey.Close();
            User32Utils.Notify_SettingChange();
            WinINetUtils.Notify_OptionSettingChanges();
        }
    }
}

WinINetUtils.cs

This class is useful to notify Internet Explorer about the changes made in the Windows registry.

C#
using System;
using System.Collections.Generic;
using System.Text;

using System.Runtime.InteropServices;

namespace RedTomahawk.TORActivator
{
    internal class WinINetUtils
    {
        #region WININET Options
        private const uint INTERNET_PER_CONN_PROXY_SERVER = 2;
        private const uint INTERNET_PER_CONN_PROXY_BYPASS = 3;
        private const uint INTERNET_PER_CONN_FLAGS = 1;

        private const uint INTERNET_OPTION_REFRESH = 37;
        private const uint INTERNET_OPTION_PROXY = 38;
        private const uint INTERNET_OPTION_SETTINGS_CHANGED = 39;
        private const uint INTERNET_OPTION_END_BROWSER_SESSION = 42;
        private const uint INTERNET_OPTION_PER_CONNECTION_OPTION = 75;

        private const uint PROXY_TYPE_DIRECT = 0x1;
        private const uint PROXY_TYPE_PROXY = 0x2;

        private const uint INTERNET_OPEN_TYPE_PROXY = 3;
        #endregion

        #region STRUCT
        struct Value1
        {
            uint dwValue;
            string pszValue;
            FILETIME ftValue;
        };

        [StructLayout(LayoutKind.Sequential)]
        struct INTERNET_PER_CONN_OPTION
        {
            uint dwOption;
            Value1 Value;
        };

        [StructLayout(LayoutKind.Sequential)]
        struct INTERNET_PER_CONN_OPTION_LIST
        {
            uint dwSize;
            [MarshalAs(UnmanagedType.LPStr, SizeConst = 256)]
            string pszConnection;
            uint dwOptionCount;
            uint dwOptionError;
            IntPtr pOptions;

        };

        [StructLayout(LayoutKind.Sequential)]
        struct INTERNET_CONNECTED_INFO
        {
            int dwConnectedState;
            int dwFlags;
        };
        #endregion

        #region Interop
        [DllImport("wininet.dll", EntryPoint = "InternetSetOptionA",
                  CharSet = CharSet.Ansi, SetLastError = true, PreserveSig = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, uint dwOption,
                                                     IntPtr pBuffer, int dwReserved);
        #endregion

        internal WinINetUtils(){ }


        internal static void Notify_OptionSettingChanges()
        {
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED,
                    IntPtr.Zero, 0);
            InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
        }
    }
}

And then the code notifies changes to Windows:

User32Utils.cs

C#
using System;
using System.Collections.Generic;
using System.Text;

using System.Runtime.InteropServices;

namespace RedTomahawk.TORActivator
{
    internal class User32Utils
    {
        #region USER32 Options
        static IntPtr HWND_BROADCAST = new IntPtr(0xffff);
        static IntPtr WM_SETTINGCHANGE = new IntPtr(0x001A);
        #endregion

        #region STRUCT
        enum SendMessageTimeoutFlags : uint
        {
            SMTO_NORMAL = 0x0000,
            SMTO_BLOCK = 0x0001,
            SMTO_ABORTIFHUNG = 0x0002,
            SMTO_NOTIMEOUTIFNOTHUNG = 0x0008
        }
        #endregion

        #region Interop
        //[DllImport("user32.dll", CharSet = CharSet.Auto)]
        //public static extern int SendMessage
        //(int hWnd, int msg, int wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern IntPtr SendMessageTimeout(IntPtr hWnd,
                                                uint Msg,
                                                UIntPtr wParam,
                                                UIntPtr lParam,
                                                SendMessageTimeoutFlags fuFlags,
                                                uint uTimeout,
                                                out UIntPtr lpdwResult);
        #endregion


        internal User32Utils() { }

        internal static void Notify_SettingChange()
        {
            UIntPtr result;
            SendMessageTimeout(HWND_BROADCAST, (uint)WM_SETTINGCHANGE,
                               UIntPtr.Zero, UIntPtr.Zero,
                                SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out result);
        }
    }
}

The CEngine class calls all the required procedures:

CEngine.cs

C#
using System;
using System.Collections.Generic;
using System.Text;

namespace RedTomahawk.TORActivator
{
    public class CEngine
    {
        RegUtils _regUtils = new RegUtils();

        public CEngine() { }

        public void SetProxyName(string ProxyAddress)
        {
            string szRegKey =
                @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\";
            string szName = "ProxyServer";

            _regUtils.SetKeyValue(RegUtils.RegKeyType.CurrentUser,
                                   szRegKey, szName, ProxyAddress);
        }

        public void EnableProxy(string ProxyAddress)
        {
            string szRegKey =
                 @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\";
            string szName = "ProxyEnable";
            string szValue = string.Empty;

            _regUtils.GetKeyValue(RegUtils.RegKeyType.CurrentUser,
                    szRegKey, "ProxyServer", out szValue);

            if (szValue != ProxyAddress)
            {
                SetProxyName(ProxyAddress);
            }

            _regUtils.SetKeyValue(RegUtils.RegKeyType.CurrentUser, szRegKey, szName, 1);

            byte[] abValue;
            char[] aaValue;
            szRegKey = szRegKey + "Connections";
            _regUtils.GetKeyValue(RegUtils.RegKeyType.CurrentUser, szRegKey,
                                   "DefaultConnectionSettings", out abValue);
            aaValue = new char[abValue.Length];

            // This procedure enable the Proxy for IE7
            for (int i = 0; i < abValue.Length; i++)
            {
                if (i == 8)
                    abValue[i] = 3;
                aaValue[i] = (char)abValue[i];
            }


            _regUtils.SetKeyValue(RegUtils.RegKeyType.CurrentUser, szRegKey,
                                  "DefaultConnectionSettings",
                                  Encoding.ASCII.GetBytes(
                                  (new string(aaValue)).Replace(szValue, ProxyAddress)));
        }

        public void DisableProxy(string ProxyAddress)
        {
            string szRegKey =
                @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\";
            string szName = "ProxyEnable";
            _regUtils.SetKeyValue(RegUtils.RegKeyType.CurrentUser,
                                   szRegKey, szName, 0);

            byte[] abValue;
            szRegKey = szRegKey + "Connections";
            _regUtils.GetKeyValue(RegUtils.RegKeyType.CurrentUser, szRegKey,
                                  "DefaultConnectionSettings", out abValue);

            for (int i = 0; i < abValue.Length; i++)
            {
                //This procedure disable proxy
                if (i == 8)
                {
                    abValue[i] = 0;
                    break;
                }
            }
            _regUtils.SetKeyValue(RegUtils.RegKeyType.CurrentUser,
                         szRegKey, "DefaultConnectionSettings", abValue);
        }

        public string GetProxyName()
        {
            string szRegKey =
                 @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\";
            string szName = "ProxyServer";
            string szProxyAddress = string.Empty;

            _regUtils.GetKeyValue(RegUtils.RegKeyType.CurrentUser, szRegKey,
                                    szName, out szProxyAddress);

            return szProxyAddress;
        }

        public int GetProxyStatus()
        {
            string szRegKey =
                 @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\";
            string szName = "ProxyEnable";
            int iProxyStatus = 0;

            _regUtils.GetKeyValue(RegUtils.RegKeyType.CurrentUser,
                                  szRegKey, szName, out iProxyStatus);

            return iProxyStatus;
        }
    }
}

Points of Interest

This software is useful to those Internet users who need to or want to use different proxies during surfing.

Thanks to this software, you can change a proxy automatically without restarting Internet Explorer. For example, if while surfing, you need to keep your IP anonymity (for example, using TOR), you just need to press a checkbox to change your Internet Explorer proxy settings.

History

  • 4th October, 2007 -- Original version posted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWant to also set and get the Automatically Detect Settings Pin
rsnyder4-Oct-13 10:09
rsnyder4-Oct-13 10:09 
QuestionTOR Activator GUI Pin
SysEng697-May-13 11:39
SysEng697-May-13 11:39 
AnswerRe: TOR Activator GUI Pin
rsnyder4-Oct-13 9:55
rsnyder4-Oct-13 9:55 
AnswerRe: TOR Activator GUI Pin
rsnyder4-Oct-13 9:56
rsnyder4-Oct-13 9:56 
QuestionCan you send me the whole code include where to start and how... Pin
Eyal9194-Aug-10 11:23
Eyal9194-Aug-10 11:23 
GeneralNo Form is included in the code Pin
Farrukh Rehman23-Jun-09 7:37
Farrukh Rehman23-Jun-09 7:37 
GeneralLocalMachine vs. CurrentUser Pin
Ossan Dust25-Sep-08 23:47
Ossan Dust25-Sep-08 23:47 
GeneralIE6 Pin
bogdandanielb1-Sep-08 0:24
bogdandanielb1-Sep-08 0:24 
GeneralPls UPload the Whole project . Pin
kothanzaw6-Dec-07 16:38
kothanzaw6-Dec-07 16:38 
GeneralProblem occured - registry damaged [modified] Pin
schleicher17-Nov-07 2:04
schleicher17-Nov-07 2:04 
GeneralRe: Problem occured - registry damaged Pin
Manuel C17-Nov-07 2:57
Manuel C17-Nov-07 2:57 
GeneralRe: Problem occured - registry damaged [modified] Pin
schleicher17-Nov-07 9:08
schleicher17-Nov-07 9:08 
Sorry - but that didn't help eigther for me...
I used your code to write some other classes, which - if the ProxyServer-Key doesn't exist - uses the DefaultConnectionSettings.

public abstract class ProxySetting
{
    RedTomahawk.TORActivator.RegUtils regUtils = new RedTomahawk.TORActivator.RegUtils();
    protected RedTomahawk.TORActivator.RegUtils RegUtils { get { return regUtils; } }

    protected string proxyAddress = "";
    protected bool proxyEnabled = false;
    protected bool proxyBypass = false;

    public string ProxyAddress { get { return proxyAddress; } set { proxyAddress = value; } }
    public bool ProxyEnabled { get { return proxyEnabled; } set { proxyEnabled = value; } }
    public bool ProxyBypass { get { return proxyBypass; } set { proxyBypass = value; } }

    public abstract void Get();
    public abstract void Put();
}

public class ProxySimple : ProxySetting
{
    const string RegKey = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
    const string ProxyKeyName = "ProxyServer";
    const string EnabledKeyName = "ProxyEnable";
    const string BypassKeyName = "ProxyOverride";

    public override void Get()
    {
        try
        {
            RegUtils.GetKeyValue(RedTomahawk.TORActivator.RegUtils.RegKeyType.CurrentUser, RegKey, ProxyKeyName, out proxyAddress);

            int enabled;
            RegUtils.GetKeyValue(RedTomahawk.TORActivator.RegUtils.RegKeyType.CurrentUser, RegKey, EnabledKeyName, out enabled);
            proxyEnabled = (enabled == 1);

            string bypass;
            RegUtils.GetKeyValue(RedTomahawk.TORActivator.RegUtils.RegKeyType.CurrentUser, RegKey, BypassKeyName, out bypass);
            proxyBypass = (bypass == "<local>");
        }
        catch { }
    }

    public override void Put()
    {
        RegUtils.SetKeyValue(RedTomahawk.TORActivator.RegUtils.RegKeyType.CurrentUser, RegKey, ProxyKeyName, proxyAddress);

        RegUtils.SetKeyValue(RedTomahawk.TORActivator.RegUtils.RegKeyType.CurrentUser, RegKey, EnabledKeyName, (proxyEnabled ? 1 : 0));

        RegUtils.SetKeyValue(RedTomahawk.TORActivator.RegUtils.RegKeyType.CurrentUser, RegKey, BypassKeyName, (proxyBypass ? "<local>" : "127.0.0.1"));
    }
}

public class ProxyExtended : ProxySetting
{
    const string RegKey = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections";
    const string KeyName = "DefaultConnectionSettings";
    /*
        0.  keep this value
        1.  "00" placeholder
        2.  "00" placeholder
        3.  "00" placeholder
        4.  "xx" increments if changed
        5.  "xx" increments if 4. is "FF"
        6.  "00" placeholder
        7.  "00" placeholder
        8.  "01"=proxy deaktivated; other value=proxy enabled
        9.  "00" placeholder
        10. "00" placeholder
        11. "00" placeholder
        12. "xx" length of "proxyserver:port"
        13. "00" placeholder
        14. "00" placeholder
        15. "00" placeholder
        "proxyserver:port"
    if 'Bypass proxy for local addresses':::
        other stuff with unknown length
        "<local>"
        36 times "00"
    if no 'Bypass proxy for local addresses':::
        40 times "00"
    */

    public override void Get()
    {
        byte[] ar;
        RegUtils.GetKeyValue(RedTomahawk.TORActivator.RegUtils.RegKeyType.CurrentUser, RegKey, KeyName, out ar);

        proxyEnabled = (ar[8] != 1);

        int i = 16;
        proxyAddress = "";
        for (; ar[i] != 7 && ar[i] != 0; i++)
            proxyAddress += System.Convert.ToChar(ar[i]).ToString();

        string bypass = "";
        while (i < ar.Length)
        {
            bypass = "";
            for (int j = i; ar[j] != 0; j++)
                bypass += System.Convert.ToChar(ar[j]).ToString();
            i++;
            if (bypass.Contains("<local>"))
                break;
        }
        proxyBypass = (bypass.Contains("<local>"));
    }

    public override void Put()
    {
        byte[] ar;
        RegUtils.GetKeyValue(RedTomahawk.TORActivator.RegUtils.RegKeyType.CurrentUser, RegKey, KeyName, out ar);

        System.Collections.Generic.List<byte> l = new System.Collections.Generic.List<byte>();
        for (int i = 0; i < 16; i++)
            if (i == 4)
            {
                if (ar[i] > 0)
                    l.Add(0);
                else
                    l.Add(1);
            }
            else if (i == 5)
                l.Add(0);
            else if (i == 8)
                l.Add((byte)((proxyEnabled) ? 3 : 1));
            else if (i == 12)
                l.Add((byte)proxyAddress.Length);
            else
                l.Add(ar[i]);
        foreach (char c in proxyAddress)
            l.Add(System.Convert.ToByte(c));
        if (proxyBypass)
        {
            l.Add(7);
            l.Add(0); l.Add(0); l.Add(0);
            foreach (char c in "<local>")
                l.Add(System.Convert.ToByte(c));
            for (int i = 0; i < 36; i++)
                l.Add(0);
        }
        else
            for (int i = 0; i < 40; i++)
                l.Add(0);

        RegUtils.SetKeyValue(RedTomahawk.TORActivator.RegUtils.RegKeyType.CurrentUser, RegKey, KeyName, l.ToArray());
    }
}

public class ProxySettings : System.Collections.Generic.List<ProxySetting>
{
    public string ProxyAddress
    {
        get
        {
            foreach (ProxySetting ps in this)
                if (!string.IsNullOrEmpty(ps.ProxyAddress))
                    return ps.ProxyAddress;
            return "";
        }
        set { foreach (ProxySetting ps in this) ps.ProxyAddress = value; }
    }

    public bool ProxyEnabled
    {
        get
        {
            bool b = true;
            foreach (ProxySetting ps in this)
                b &= ps.ProxyEnabled;
            return b;
        }
        set { foreach (ProxySetting ps in this) ps.ProxyEnabled = value; }
    }

    public bool ProxyBypass
    {
        get
        {
            bool b = true;
            foreach (ProxySetting ps in this)
                b &= ps.ProxyBypass;
            return b;
        }
        set { foreach (ProxySetting ps in this) ps.ProxyBypass = value; }
    }

    public void Get() { foreach (ProxySetting ps in this) ps.Get(); }

    public void Put() { foreach (ProxySetting ps in this) ps.Put(); }

    public static ProxySettings GetSimpleAndExtended()
    {
        ProxySettings psl = new ProxySettings();
        psl.Add(new ProxySimple());
        psl.Add(new ProxyExtended());

        for (int i = 0; i < psl.Count; i++)
        {
            psl[i].Get();
            if (string.IsNullOrEmpty(psl[i].ProxyAddress)) { psl.RemoveAt(i); i--; }
        }

        return psl;
    }
}



-- modified at 12:43 Sunday 18th November, 2007
GeneralIE7 Pin
CARPETBURNER4-Oct-07 11:22
CARPETBURNER4-Oct-07 11:22 
GeneralRe: IE7 Pin
Manuel C4-Oct-07 11:57
Manuel C4-Oct-07 11:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.