C#设置IE代理

首先,我想通过修改注册表来设置IE代理。

以下是修改注册表的代码:

[csharp]  view plain copy
  1. //打开注册表  
  2. Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings"true);              
  3. //设置代理  
  4. rk.SetValue("ProxyEnable", 1);  
  5. rk.SetValue("ProxyServer""8.8.8.8:8000");  
  6. //取消代理  
  7. //rk.SetValue("ProxyEnable", 0);  
  8.   
  9. rk.Flush(); //刷新注册表  
  10. rk.Close();  

然后调用 WinInet API ,激活代理设置。

[csharp]  view plain copy
  1. [DllImport(@"wininet",   
  2.     SetLastError = true,   
  3.     CharSet = CharSet.Auto,   
  4.     EntryPoint = "InternetSetOption",  
  5.     CallingConvention = CallingConvention.StdCall)]  
  6. public static extern bool InternetSetOption(  
  7.     int hInternet,  
  8.     int dmOption,  
  9.     IntPtr lpBuffer,  
  10.     int dwBufferLength  
  11. );  
  12.   
  13. void SetProxy() {  
  14.     //打开注册表  
  15.     Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings"true);              
  16.     //设置代理  
  17.     rk.SetValue("ProxyEnable", 1);  
  18.     rk.SetValue("ProxyServer""8.8.8.8:8000");  
  19.     //取消代理  
  20.     //rk.SetValue("ProxyEnable", 0);  
  21.   
  22.     rk.Flush(); //刷新注册表  
  23.     rk.Close();  
  24.     //激活代理设置  
  25.     InternetSetOption(0, 39, IntPtr.Zero, 0);  
  26.     InternetSetOption(0, 37, IntPtr.Zero, 0);  
  27. }  

到这里,应该能成功设置代理了,但是问题出现了,无法正常设置代理。

我的系统是Win7 专业版,在网上搜了一遍后发现,有人说这段代码在XP下能work,win7下会失效。

InternetSetOption()函数Win7下失效

有人还发现:在window7下, 在一个进程中, 设置和取消不能都执行,---- 要么设置,要么取消。 但如果第一次运行时,只进行设置代理,退出后再进运行,只进行取消,这是没有问题的。

简单说说他给出的解决方案:每次设置或取消代理时,都新建一个进程,在新的进程中处理,处理完之后关掉进程。

这种方法可以work,但显得很蛋疼。

所以我没采用这种方法。


最后,找着国外一大神 Joel 'Jaykul' Bennett 的一篇文章Setting Windows internet connection proxy from C#

试了一下,完美解决。

代码如下:

[csharp]  view plain copy
  1. using System;  
  2. using System.Runtime.InteropServices;  
  3. using System.ComponentModel;  
  4.   
  5. namespace PoshHttp  
  6. {  
  7.    public class Proxies  
  8.    {  
  9.       public static bool UnsetProxy()  
  10.       {  
  11.          return SetProxy(nullnull);  
  12.       }  
  13.       public static bool SetProxy(string strProxy)  
  14.       {  
  15.          return SetProxy(strProxy, null);  
  16.       }  
  17.   
  18.       public static bool SetProxy(string strProxy, string exceptions)  
  19.       {  
  20.          InternetPerConnOptionList list = new InternetPerConnOptionList();  
  21.   
  22.          int optionCount = string.IsNullOrEmpty(strProxy) ? 1 : (string.IsNullOrEmpty(exceptions) ? 2 : 3);  
  23.          InternetConnectionOption[] options = new InternetConnectionOption[optionCount];  
  24.          // USE a proxy server ...  
  25.          options[0].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;  
  26.          options[0].m_Value.m_Int = (int)((optionCount < 2) ? PerConnFlags.PROXY_TYPE_DIRECT : (PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY));  
  27.          // use THIS proxy server  
  28.          if (optionCount > 1)  
  29.          {  
  30.             options[1].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER;  
  31.             options[1].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(strProxy);  
  32.             // except for these addresses ...  
  33.             if (optionCount > 2)  
  34.             {  
  35.                options[2].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPASS;  
  36.                options[2].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(exceptions);  
  37.             }  
  38.          }  
  39.   
  40.          // default stuff  
  41.          list.dwSize = Marshal.SizeOf(list);  
  42.          list.szConnection = IntPtr.Zero;  
  43.          list.dwOptionCount = options.Length;  
  44.          list.dwOptionError = 0;  
  45.   
  46.   
  47.          int optSize = Marshal.SizeOf(typeof(InternetConnectionOption));  
  48.          // make a pointer out of all that ...  
  49.          IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length);  
  50.          // copy the array over into that spot in memory ...  
  51.          for (int i = 0; i < options.Length; ++i)  
  52.          {  
  53.             IntPtr opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize));  
  54.             Marshal.StructureToPtr(options[i], opt, false);  
  55.          }  
  56.   
  57.          list.options = optionsPtr;  
  58.   
  59.          // and then make a pointer out of the whole list  
  60.          IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((Int32)list.dwSize);  
  61.          Marshal.StructureToPtr(list, ipcoListPtr, false);  
  62.   
  63.          // and finally, call the API method!  
  64.          int returnvalue = NativeMethods.InternetSetOption(IntPtr.Zero,  
  65.             InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION,   
  66.             ipcoListPtr, list.dwSize) ? -1 : 0;  
  67.          if (returnvalue == 0)  
  68.          {  // get the error codes, they might be helpful  
  69.             returnvalue = Marshal.GetLastWin32Error();  
  70.          }  
  71.          // FREE the data ASAP  
  72.          Marshal.FreeCoTaskMem(optionsPtr);  
  73.          Marshal.FreeCoTaskMem(ipcoListPtr);  
  74.          if (returnvalue > 0)  
  75.          {  // throw the error codes, they might be helpful  
  76.             throw new Win32Exception(Marshal.GetLastWin32Error());  
  77.          }  
  78.   
  79.          return (returnvalue < 0);  
  80.       }  
  81.    }  
  82.  
  83.    #region WinInet structures  
  84.    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]  
  85.    public struct InternetPerConnOptionList  
  86.    {  
  87.       public int dwSize;               // size of the INTERNET_PER_CONN_OPTION_LIST struct  
  88.       public IntPtr szConnection;         // connection name to set/query options  
  89.       public int dwOptionCount;        // number of options to set/query  
  90.       public int dwOptionError;           // on error, which option failed  
  91.       //[MarshalAs(UnmanagedType.)]  
  92.       public IntPtr options;  
  93.    };  
  94.   
  95.    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]  
  96.    public struct InternetConnectionOption  
  97.    {  
  98.       static readonly int Size;  
  99.       public PerConnOption m_Option;  
  100.       public InternetConnectionOptionValue m_Value;  
  101.       static InternetConnectionOption()  
  102.       {  
  103.          InternetConnectionOption.Size = Marshal.SizeOf(typeof(InternetConnectionOption));  
  104.       }  
  105.   
  106.       // Nested Types  
  107.       [StructLayout(LayoutKind.Explicit)]  
  108.       public struct InternetConnectionOptionValue  
  109.       {  
  110.          // Fields  
  111.          [FieldOffset(0)]  
  112.          public System.Runtime.InteropServices.ComTypes.FILETIME m_FileTime;  
  113.          [FieldOffset(0)]  
  114.          public int m_Int;  
  115.          [FieldOffset(0)]  
  116.          public IntPtr m_StringPtr;  
  117.       }  
  118.    }  
  119.    #endregion  
  120.  
  121.    #region WinInet enums  
  122.    //  
  123.    // options manifests for Internet{Query|Set}Option  
  124.    //  
  125.    public enum InternetOption : uint  
  126.    {  
  127.       INTERNET_OPTION_PER_CONNECTION_OPTION = 75  
  128.    }  
  129.   
  130.    //  
  131.    // Options used in INTERNET_PER_CONN_OPTON struct  
  132.    //  
  133.    public enum PerConnOption  
  134.    {  
  135.       INTERNET_PER_CONN_FLAGS = 1, // Sets or retrieves the connection type. The Value member will contain one or more of the values from PerConnFlags   
  136.       INTERNET_PER_CONN_PROXY_SERVER = 2, // Sets or retrieves a string containing the proxy servers.    
  137.       INTERNET_PER_CONN_PROXY_BYPASS = 3, // Sets or retrieves a string containing the URLs that do not use the proxy server.    
  138.       INTERNET_PER_CONN_AUTOCONFIG_URL = 4//, // Sets or retrieves a string containing the URL to the automatic configuration script.    
  139.   
  140.    }  
  141.   
  142.    //  
  143.    // PER_CONN_FLAGS  
  144.    //  
  145.    [Flags]  
  146.    public enum PerConnFlags  
  147.    {  
  148.       PROXY_TYPE_DIRECT = 0x00000001,  // direct to net  
  149.       PROXY_TYPE_PROXY = 0x00000002,  // via named proxy  
  150.       PROXY_TYPE_AUTO_PROXY_URL = 0x00000004,  // autoproxy URL  
  151.       PROXY_TYPE_AUTO_DETECT = 0x00000008   // use autoproxy detection  
  152.    }  
  153.    #endregion  
  154.   
  155.    internal static class NativeMethods  
  156.    {  
  157.       [DllImport("WinInet.dll", SetLastError = true, CharSet = CharSet.Auto)]  
  158.       [return: MarshalAs(UnmanagedType.Bool)]  
  159.       public static extern bool InternetSetOption(IntPtr hInternet, InternetOption dwOption, IntPtr lpBuffer, int dwBufferLength);  
  160.    }  
  161. }  


开源代码:

https://github.com/NoNeil/ProxySetting


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值