C# WebBrowser设置代理

WebBrowser控件是基于IE浏览器的,所以它的内核功能是依赖于IE.

code:
 
    class IEProxy
    {
        //设置代理选项                
        private const int INTERNET_OPTION_PROXY = 38;
        //设置代理类型                
        private const int INTERNET_OPEN_TYPE_PROXY = 3;                
        //设置代理类型,直接访问,不需要通过代理服务器
        private const int INTERNET_OPEN_TYPE_DIRECT = 1;

        private string ProxyStr;

        //You can change the proxy with InternetSetOption method from the wininet.dll                
        //这个就是设置一个Internet 选项。设置代理是Internet 选项其中的一个功能
        [System.Runtime.InteropServices.DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);

        //定义代理信息的结构体                  
        public struct Struct_INTERNET_PROXY_INFO
        {
            public int dwAccessType;
            public IntPtr proxy;
            public IntPtr proxyBypass;
        }
       //设置代理的方法
       //strProxy为代理IP:端口        
        private bool InternetSetOption(string strProxy)
        {
            int bufferLength;
            IntPtr intptrStruct;
            Struct_INTERNET_PROXY_INFO struct_IPI;
            
            //Filling in structure 
            if (string.IsNullOrEmpty(strProxy) || strProxy.Trim().Length == 0)
            {
                strProxy = string.Empty;
                struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_DIRECT;

            }
            else
            {
                struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
            }
            //把代理地址设置到非托管内存地址中
            struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy);
            //代理通过本地连接到代理服务器上
            struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local");
            bufferLength = Marshal.SizeOf(struct_IPI);

            //Allocating memory
            //关联到内存
            intptrStruct = Marshal.AllocCoTaskMem(bufferLength);

           //Converting structure to IntPtr 
           //把结构体转换到句柄
            Marshal.StructureToPtr(struct_IPI, intptrStruct, true);
            return InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, bufferLength);
        }
        public IEProxy(string strProxy)
        {
            this.ProxyStr = strProxy;
        }
        //设置代理
        public bool SetIESettings()
        {
            return InternetSetOption(this.ProxyStr);
        }
        //取消代理
        public bool DisableIEProxy()
        {
            return InternetSetOption(string.Empty);
        }
    }
posted @ 2013-09-11 16:46  沧海一滴  阅读(1389)  评论(0编辑  收藏  举报