C# WebBrowser設定代理

滄海一滴發表於2013-09-11
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);
        }
    }

相關文章