C#设置IE代理
首先,我想通過修改注冊表來設置IE代理。
以下是修改注冊表的代碼:
//打開注冊表 Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); //設置代理 rk.SetValue("ProxyEnable", 1); rk.SetValue("ProxyServer", "8.8.8.8:8000"); //取消代理 //rk.SetValue("ProxyEnable", 0);rk.Flush(); //刷新注冊表 rk.Close();然后調用 WinInet API ,激活代理設置。
[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 );void SetProxy() {//打開注冊表Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true); //設置代理rk.SetValue("ProxyEnable", 1);rk.SetValue("ProxyServer", "8.8.8.8:8000");//取消代理//rk.SetValue("ProxyEnable", 0);rk.Flush(); //刷新注冊表rk.Close();//激活代理設置InternetSetOption(0, 39, IntPtr.Zero, 0);InternetSetOption(0, 37, IntPtr.Zero, 0); }
到這里,應該能成功設置代理了,但是問題出現了,無法正常設置代理。
我的系統是Win7 專業版,在網上搜了一遍后發現,有人說這段代碼在XP下能work,win7下會失效。
InternetSetOption()函數Win7下失效
有人還發現:在window7下, 在一個進程中, 設置和取消不能都執行,---- 要么設置,要么取消。 但如果第一次運行時,只進行設置代理,退出后再進運行,只進行取消,這是沒有問題的。
簡單說說他給出的解決方案:每次設置或取消代理時,都新建一個進程,在新的進程中處理,處理完之后關掉進程。
這種方法可以work,但顯得很蛋疼。
所以我沒采用這種方法。
最后,找著國外一大神?Joel 'Jaykul' Bennett?的一篇文章Setting Windows internet connection proxy from C#
試了一下,完美解決。
代碼如下:
using System; using System.Runtime.InteropServices; using System.ComponentModel;namespace PoshHttp {public class Proxies{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 serverif (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 stufflist.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 listIntPtr 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 helpfulreturnvalue = Marshal.GetLastWin32Error();}// FREE the data ASAPMarshal.FreeCoTaskMem(optionsPtr);Marshal.FreeCoTaskMem(ipcoListPtr);if (returnvalue > 0){ // throw the error codes, they might be helpfulthrow 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 structpublic IntPtr szConnection; // connection name to set/query optionspublic int dwOptionCount; // number of options to set/querypublic 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 netPROXY_TYPE_PROXY = 0x00000002, // via named proxyPROXY_TYPE_AUTO_PROXY_URL = 0x00000004, // autoproxy URLPROXY_TYPE_AUTO_DETECT = 0x00000008 // use autoproxy detection}#endregioninternal 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);} }開源代碼:
https://github.com/NoNeil/ProxySetting
總結
- 上一篇: crh寄存器_STM32直接操作寄存器
- 下一篇: 第4章 集合框架