基于c#的IE 代理服务器设置


在进行IE代理服务设置时,需要手动打开代理服务器以及设置IE浏览器代理设置、开启或关闭。此处利用c#编写窗体,一键打开代理服务器、设置IE代理。此程序是基于一改进方案进行开发。一般的做法是直接修改注册表进行IE代理的设置,但是需要重启浏览器才能生效,改进方案中修正这一弊端,在浏览器运行时就能正常设置代理,但是不涉及代理服务器。此程序可以调用已经配置好的代理服务器,在开启代理后,能直接访问需要代理的网站,此程序经过安装部署处理。

主要程序的将在最后显示。
以下记录使用的部分程序:
1.计算已使用此代理程序时间:
DateTime start_time = DateTime.Now;
 private void show_timer_Tick(object sender, EventArgs e)
        {
            DateTime time_now = DateTime.Now;
            date_label.Text = time_now.ToShortDateString();
            time_label.Text = time_now.ToShortTimeString();
            TimeSpan time_begin = new TimeSpan(start_time.Ticks);
            TimeSpan time_end= new TimeSpan(time_now.Ticks);
            TimeSpan time_span = time_end.Subtract(time_begin).Duration();
            usedTime_label.Text ="Used "+ time_span.Hours.ToString() + " hours" + " "+time_span.Minutes.ToString() + " mins";

        }
主要使用 TimeSpan 以及 Timer 控件。此处同时显示了当前时间。

2, 获取计算机的有关信息,电脑名,用户名,处理器数量,电脑物理地址,操作系统版本,运行时的共同语言(基本不需要)。

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            computer_info_listBox.Items.Add("computer name:" );
            computer_info_listBox.Items.Add( Environment.MachineName);
            computer_info_listBox.Items.Add("user name:" );
            computer_info_listBox.Items.Add( Environment.UserName);
            computer_info_listBox.Items.Add("processor count:" );
            computer_info_listBox.Items.Add( Environment.ProcessorCount);
            computer_info_listBox.Items.Add("computer mac address:");
             computer_info_listBox.Items.Add( GetNetworkAdapterID());
     
            computer_info_listBox.Items.Add("Operation system version:" );
            computer_info_listBox.Items.Add(Environment.OSVersion);
            computer_info_listBox.Items.Add("common language running:");
            computer_info_listBox.Items.Add(Environment.Version);
此段代码被放置在组件初始化程序( InitializeComponent();)后面。
其中,获取电脑物理地址调用了自定义的函数。函数定义如下
public static string GetNetworkAdapterID()
        {
            
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetWorkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                   if((bool)mo["IPEnabled"]==true)
                        mac = mo["MacAddress"].ToString();
                        
                }

                return mac;
        }
网上有关物理地址获取的方式较多。此处是参考官网上的实例。网上的此种方法函数定义稍复杂,测试发现,有些不一定能使用。

3.打开,关闭代理服务器程序
打开代理服务器
将代理服务器文件放在debug文件下,包括.exe文件。然后在开启IE代理设置的同时,执行此程序。
           System.Diagnostics.Process.Start(@".\proxyfile\local\<span style="line-height: 29.7000007629395px; white-space: pre-wrap; font-family: 'microsoft yahei';">proxy</span>.exe");
此处的proxyfile是包含.exe的文件。proxy是代理服务器名,此处没有填写自己正在使用的代理服务器名。

关闭代理服务器程序
 public void KillProcess(string ProName)
        {
            Process[] Goagent_proxy = Process.GetProcessesByName(ProName);
          
            foreach(Process p_kill in Goagent_proxy)
            {
                p_kill.Kill();
            }
        }
关闭正在运行的代理服务器是通过调用以上函数完成的,其中函数的参数是代理服务器名,即proxy.exe中的 proxy
此处主要使用 process 类,具体使用可以参考相关文档。

4.关闭messagebox执行事件。此处是打开一网址。
 DialogResult message_Result=  MessageBox.Show("Step1: Import certificate from goagent, detail operation,see:" + "\n" + "    when you click the OK below,you will see the article " +"\n"+"Step2: click setting proxy button in the interface", "Instruction",MessageBoxButtons.OK);
          if (message_Result == DialogResult.OK)
          {
              Process.Start("http://jingyan.baidu.com/article/8275fc869f1c0c46a03cf6e9.html ");
          }
        }




5 安装部署
此处使用的visual studio2012版,与2010版不同,需要手动下载InstallShiled.步骤如下;
打开 VS, new -- project -- Installed--template--other Project Types --Setup and Deployment ,选择ok后者中间的 InstallShield Limited Edition Project,将在浏览器中打开下载改程序的网页,在右侧填写相关信息。然后下载。
注意,若国家、城市等无法打开下拉选框进行填写时,表明这是Great Wall 在发挥作用,解决办法是使用代理服务器打开此页面。
后面的步骤就是下载安装 InstallShield。 注意,安装之前要关闭VS,同时,右键安装程序,以管理员身份运行
完成后,按照之前的步骤重新操作,即可。


程序源码
ProxySeting.cs:
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;
using System.IO;
namespace IEProxyManagment
{
    public partial class ProxySeting : Form
    {
        DateTime start_time = DateTime.Now;
        public ProxySeting()
        {
            InitializeComponent();
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            computer_info_listBox.Items.Add("computer name:" );
            computer_info_listBox.Items.Add( Environment.MachineName);
            computer_info_listBox.Items.Add("user name:" );
            computer_info_listBox.Items.Add( Environment.UserName);
            computer_info_listBox.Items.Add("processor count:" );
            computer_info_listBox.Items.Add( Environment.ProcessorCount);
            computer_info_listBox.Items.Add("computer mac address:");
             computer_info_listBox.Items.Add( GetNetworkAdapterID());
     
            computer_info_listBox.Items.Add("Operation system version:" );
            computer_info_listBox.Items.Add(Environment.OSVersion);
            computer_info_listBox.Items.Add("common language running:");
            computer_info_listBox.Items.Add(Environment.Version);

            //DateTime start_time = DateTime.Now;
           
        }

        public static string GetNetworkAdapterID()
        {
            
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetWorkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                   if((bool)mo["IPEnabled"]==true)
                        mac = mo["MacAddress"].ToString();
                        
                }

                return mac;
        }
       /* public static List<string> GetMacByIPConfig()
        {
            List<string> macs = new List<string>();
            ProcessStartInfo startInfo = new ProcessStartInfo("ipconfig", "/all");
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.CreateNoWindow = false;
            Process p = Process.Start(startInfo);

            StreamReader reader = p.StandardOutput;
            string line = reader.ReadLine();
            while (!reader.EndOfStream)
            {
                if (string.IsNullOrEmpty(line))
                {
                    line = line.Trim();

                    if (line.StartsWith("Physical Address"))
                    {
                        macs.Add(line);
                    }
                }
                line = reader.ReadLine();
            }
            p.WaitForExit();
            p.Close();
            reader.Close();

            return macs;
        }   */
               
        private void btnSetProxy_Click(object sender, EventArgs e)
        {
           System.Diagnostics.Process.Start(@".\proxyfile\local\proxy.exe");
            string proxyStr = combProxyList.Text.Trim();
            IEProxySetting.SetProxy(proxyStr, null);
            var currentProxy = GetProxyServer();
            if (currentProxy == proxyStr && GetProxyStatus())
            {
                lblInfo.Text = "Setting Proxy:" + proxyStr + "  successfully!";
                lblInfo.ForeColor = Color.Green;
            }
            else
            {
                if (!GetProxyStatus())
                {
                    lblInfo.Text = "Setting Proxy:" + proxyStr + "Proxy does not work!";

                }
                else
                {
                    lblInfo.Text = "Setting Proxy:" + proxyStr + "failed,It is using" + currentProxy + "Proxy,please try!";

                }
                lblInfo.ForeColor = Color.Red;
            }
            ShowProxyInfo();
            btnSetProxy.Enabled = false;
            btnDisableProxy.Enabled = true;
        }

        private void ProxySetingWin_Load(object sender, EventArgs e)
        {
            ShowProxyInfo();
            InitProxyData();
        }

        /// <summary>
        /// 获取正在使用的代理
        /// </summary>
        /// <returns></returns>
        private string GetProxyServer()
        {
            //打开注册表 
            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);             //更改健值,设置代理, 
            string actualProxy = optionKey.GetValue("ProxyServer").ToString();
            regKey.Close();
            return actualProxy;
        }

        private bool GetProxyStatus()
        {
            //打开注册表 
            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);             //更改健值,设置代理, 
            int actualProxyStatus = Convert.ToInt32(optionKey.GetValue("ProxyEnable"));
            regKey.Close();
            return actualProxyStatus == 1 ? true : false;
        }

        private void ShowProxyInfo()
        {
            if (!GetProxyStatus())
            {
                lblInitInfo.Text = "Proxy Disabled:";
            }
            else
            {
                lblInitInfo.Text = "Current using Proxy is:" + GetProxyServer();
            }
        }

        private void InitProxyData()
        {
            List<string> proxyList = new List<string>{
               "127.0.0.1:8087","127.0.0.1:8088"
           };
            combProxyList.DataSource = proxyList;
            combProxyList.SelectedIndex = 0;
        }
        public void KillProcess(string ProName)
        {
            Process[] Goagent_proxy = Process.GetProcessesByName(ProName);
          
            foreach(Process p_kill in Goagent_proxy)
            {
                p_kill.Kill();
            }
        }

        private void btnDisableProxy_Click(object sender, EventArgs e)
        {
            
            KillProcess("proxy");
            IEProxySetting.UnsetProxy();
            if (!GetProxyStatus())
            {
                lblInfo.Text = "Diable Proxy successfully!";
                lblInfo.ForeColor = Color.Green;
                btnSetProxy.Enabled = true;
                btnDisableProxy.Enabled = false;
            }
            else
            {
                lblInfo.Text = "fail to cancle,using Proxy " + GetProxyServer();
                lblInfo.ForeColor = Color.Red;
                btnSetProxy.Enabled = false;
                btnDisableProxy.Enabled = true;
            }
            ShowProxyInfo();
          //  btnSetProxy.FlatAppearance.BorderSize = 0;//去边线
            btnSetProxy.Enabled = true;
            btnDisableProxy.Enabled = false;
        }

        private void btnSetProxy_MouseEnter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Hand;
            btnSetProxy.BackColor = Color.Red;
        }

        private void btnSetProxy_MouseLeave(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
            btnSetProxy.BackColor = System.Drawing.SystemColors.ControlLight;
        }

        private void btnDisableProxy_MouseEnter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Hand;
            btnDisableProxy.BackColor = Color.Red;
        }

        private void btnDisableProxy_MouseLeave(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Default;
            btnDisableProxy.BackColor = System.Drawing.SystemColors.ControlLight;
        }

      

        private void problemsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Counter any problem,please setting proxy manually"+"\n"+"Or, Contact the maker.");
        }

        private void editorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Edited by YangHong,and based on other's work" + "\n" + "Contact him with email or QQ:1368783069");
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void show_timer_Tick(object sender, EventArgs e)
        {
            DateTime time_now = DateTime.Now;
            date_label.Text = time_now.ToShortDateString();
            time_label.Text = time_now.ToShortTimeString();
            TimeSpan time_begin = new TimeSpan(start_time.Ticks);
            TimeSpan time_end= new TimeSpan(time_now.Ticks);
            TimeSpan time_span = time_end.Subtract(time_begin).Duration();
            usedTime_label.Text ="Used "+ time_span.Hours.ToString() + " hours" + " "+time_span.Minutes.ToString() + " mins";

        }

        private void instructionToolStripMenuItem_Click(object sender, EventArgs e)
        {
           // MessageBox.Show("Step1: Import certificate from goagent, detail operation,see:" + "\n" + "http://jingyan.baidu.com/article/8275fc869f1c0c46a03cf6e9.html " +"\n"+"Step2: click setting proxy button in the interface", "Instruction");
          DialogResult message_Result=  MessageBox.Show("Step1: Import certificate from goagent, detail operation,see:" + "\n" + "    when you click the OK below,you will see the article " +"\n"+"Step2: click setting proxy button in the interface", "Instruction",MessageBoxButtons.OK);
          if (message_Result == DialogResult.OK)
          {
              Process.Start("http://jingyan.baidu.com/article/8275fc869f1c0c46a03cf6e9.html ");
          }
        }
    }
}


ProxySetting_Function

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace IEProxyManagment
{
   
    public class ProxySetting_Function
    {
        public static bool UnsetProxy()
        {
            return SetProxy(null, null);
        }
        public static bool SetProxy(string strProxy)
        {
            return SetProxy(strProxy, null);
        }

        public static bool SetProxy(string strProxy, string exceptions)
        {
            InternetPerConnOptionList list = new InternetPerConnOptionList();

            int optionCount = string.IsNullOrEmpty(strProxy) ? 1 : (string.IsNullOrEmpty(exceptions) ? 2 : 3);
            InternetConnectionOption[] options = new InternetConnectionOption[optionCount];
            // USE a proxy server ...
            options[0].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
            options[0].m_Value.m_Int = (int)((optionCount < 2) ? PerConnFlags.PROXY_TYPE_DIRECT : (PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY));
            // use THIS proxy server
            if (optionCount > 1)
            {
                options[1].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER;
                options[1].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(strProxy);
                // except for these addresses ...
                if (optionCount > 2)
                {
                    options[2].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPASS;
                    options[2].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(exceptions);
                }
            }

            // default stuff
            list.dwSize = Marshal.SizeOf(list);
            list.szConnection = IntPtr.Zero;
            list.dwOptionCount = options.Length;
            list.dwOptionError = 0;


            int optSize = Marshal.SizeOf(typeof(InternetConnectionOption));
            // make a pointer out of all that ...
            IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length);
            // copy the array over into that spot in memory ...
            for (int i = 0; i < options.Length; ++i)
            {
                IntPtr opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize));
                Marshal.StructureToPtr(options[i], opt, false);
            }

            list.options = optionsPtr;

            // and then make a pointer out of the whole list
            IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((Int32)list.dwSize);
            Marshal.StructureToPtr(list, ipcoListPtr, false);

            // and finally, call the API method!
            int returnvalue = NativeMethods.InternetSetOption(IntPtr.Zero,
               InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION,
               ipcoListPtr, list.dwSize) ? -1 : 0;
            if (returnvalue == 0)
            {  // get the error codes, they might be helpful
                returnvalue = Marshal.GetLastWin32Error();
            }
            // FREE the data ASAP
            Marshal.FreeCoTaskMem(optionsPtr);
            Marshal.FreeCoTaskMem(ipcoListPtr);
            if (returnvalue > 0)
            {  // throw the error codes, they might be helpful
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            return (returnvalue < 0);
        }
    }

    #region WinInet structures
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct InternetPerConnOptionList
    {
        public int dwSize;               // size of the INTERNET_PER_CONN_OPTION_LIST struct
        public IntPtr szConnection;         // connection name to set/query options
        public int dwOptionCount;        // number of options to set/query
        public int dwOptionError;           // on error, which option failed
        //[MarshalAs(UnmanagedType.)]
        public IntPtr options;
    };

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct InternetConnectionOption
    {
        static readonly int Size;
        public PerConnOption m_Option;
        public InternetConnectionOptionValue m_Value;
        static InternetConnectionOption()
        {
            InternetConnectionOption.Size = Marshal.SizeOf(typeof(InternetConnectionOption));
        }

        // Nested Types
        [StructLayout(LayoutKind.Explicit)]
        public struct InternetConnectionOptionValue
        {
            // Fields
            [FieldOffset(0)]
            public System.Runtime.InteropServices.ComTypes.FILETIME m_FileTime;
            [FieldOffset(0)]
            public int m_Int;
            [FieldOffset(0)]
            public IntPtr m_StringPtr;
        }
    }
    #endregion

    #region WinInet enums
    //
    // options manifests for Internet{Query|Set}Option
    //
    public enum InternetOption : uint
    {
        INTERNET_OPTION_PER_CONNECTION_OPTION = 75
    }

    //
    // Options used in INTERNET_PER_CONN_OPTON struct
    //
    public enum PerConnOption
    {
        INTERNET_PER_CONN_FLAGS = 1, // Sets or retrieves the connection type. The Value member will contain one or more of the values from PerConnFlags 
        INTERNET_PER_CONN_PROXY_SERVER = 2, // Sets or retrieves a string containing the proxy servers.  
        INTERNET_PER_CONN_PROXY_BYPASS = 3, // Sets or retrieves a string containing the URLs that do not use the proxy server.  
        INTERNET_PER_CONN_AUTOCONFIG_URL = 4//, // Sets or retrieves a string containing the URL to the automatic configuration script.  

    }

    //
    // PER_CONN_FLAGS
    //
    [Flags]
    public enum PerConnFlags
    {
        PROXY_TYPE_DIRECT = 0x00000001,  // direct to net
        PROXY_TYPE_PROXY = 0x00000002,  // via named proxy
        PROXY_TYPE_AUTO_PROXY_URL = 0x00000004,  // autoproxy URL
        PROXY_TYPE_AUTO_DETECT = 0x00000008   // use autoproxy detection
    }
    #endregion

    internal static class NativeMethods
    {
        [DllImport("WinInet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool InternetSetOption(IntPtr hInternet, InternetOption dwOption, IntPtr lpBuffer, int dwBufferLength);
    }
}
















  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值