[Project Intro] Disable and enable specified web proxy in code

来源:互联网 发布:java图形界面编程工具 编辑:程序博客网 时间:2024/05/17 02:22

Introduction

Explains how to close and open your web proxy using code instead of manually configuring in Internet Options. The latter operation is quite inconvinient thus annoying when you need frequently toggle between on and off states of web proxy.

Solution

Easy! Just configure the web proxy in Windows Registry. Set key 'ProxyEnable' tozero to disable the web proxy and toone to enable it specified by another key named'ProxyServer'.

Using the code (in C#)

First, identify the web proxy with application settings wrapper class ProxySettings.ProxySettings inherits fromApplicationSettingsBase class which uses reflection to detect these attributes at run time. Most of this information gets passed to the settings provider layer, which is responsible for storage, persistence format, and so on. All attributes have a default setting value applied using DefaultSettingValue and can be modified later at run time.

/// <summary>/// Web proxy identifier/// </summary>sealed class ProxySettings : ApplicationSettingsBase{    [UserScopedSetting]    [DefaultSettingValue("10.27.7.110")]    public string Server    {        get { return (string)this["Server"]; }        set { this["Server"] = value; }    }    [UserScopedSetting]    [DefaultSettingValue("8080")]    public string Port    {        get { return (string)this["Port"]; }        set { this["Port"] = value; }    }}

Second, enable and disable the web proxy by configuring the Internet Settings in Registry.

/// <summary>/// Toggle between on and off states of specified web proxy/// </summary>/// <param name="proxy">Specify the proxy identity. Should be formated as '<ip>:<port>'</param>public void ToggleProxy(string proxy){    zhuceKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);    if (proxy == null || proxy.Length == 0) //disable web proxy    {        regKey.SetValue("ProxyEnable", 0);    }    else  // enable specified web proxy    {        regKey.SetValue("ProxyEnable", 1);        regKey.SetValue("ProxyServer", proxy);    }    regKey.Flush();    regKey.Close();    InternetSetOption(0, 39, IntPtr.Zero, 0);    InternetSetOption(0, 37, IntPtr.Zero, 0);}

Downloads

I have implemented a small Windows-Forms-based tool to easily switch between the two states of web proxy. You can modify the default proxy accordingly in ProxySettings class. Once the enable/disable button is clicked, this application goes to an icon in the notification area at the right bottom of your computer screen (via NotifyIcon).


       

Figure. The simple UI (left: proxy off ; right: proxy on)


Download Microsoft Windows Form-based web proxy on-off tool (source codes) -22k


0 0
原创粉丝点击