现在的位置: 首页 > 综合 > 正文

C# 快速设置和解除浏览器代理

2013年07月27日 ⁄ 综合 ⁄ 共 941字 ⁄ 字号 评论关闭

如题

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.Win32;

namespace ProxyFastSetting
{
    public partial class FrmMain : Form
    {
        [DllImport(@"wininet",
SetLastError = true,
CharSet = CharSet.Auto,
EntryPoint = "InternetSetOption",
CallingConvention = CallingConvention.StdCall)]
        public static extern bool InternetSetOption
        (
        int hInternet,
        int dmOption,
        IntPtr lpBuffer,
        int dwBufferLength
        );

        public FrmMain()
        {
            InitializeComponent();
        }

        private void Button1Click(object sender, EventArgs e)
        {
            SetProxy(true);
            Close();
        }

        private void Button2Click(object sender, EventArgs e)
        {
            SetProxy(false);
            Close();
        }

        public void SetProxy(bool bOpen)
        {
            //打开注册表
            var regKey = Registry.CurrentUser;
          
            const string subKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
            var optionKey = regKey.OpenSubKey(subKeyPath, true);
            //更改健值,设置代理,
            if (optionKey != null) optionKey.SetValue("ProxyEnable", bOpen?1:0);


            //激活代理设置
            InternetSetOption(0, 39, IntPtr.Zero, 0);
            InternetSetOption(0, 37, IntPtr.Zero, 0);
        }
    }
}

抱歉!评论已关闭.