C# 为WebBrowser设置代理,打开网页

时间:2023-03-08 20:55:12

WebBrowser控件是基于IE浏览器的,所以它的内核功能是依赖于IE的,相信做.NET的人都知道。

今天的主题,和上一篇文章应该是差不多的,都是通过代理来实现功能的。

请看下面的代码:

//1.定义代理信息的结构体

public struct Struct_INTERNET_PROXY_INFO 
        { 
            public int dwAccessType; 
            public IntPtr proxy; 
            public IntPtr proxyBypass; 
        };

//You can change the proxy with InternetSetOption method from the wininet.dll, here is a example to set the proxy

//这个就是设置一个Internet 选项,其实就是可以设置一个代理
        [DllImport("wininet.dll", SetLastError = true)] 
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);

//设置代理的方法

//strProxy为代理IP:端口
        private void InternetSetOption(string strProxy) 
        {

//设置代理选项

const int INTERNET_OPTION_PROXY = 38;

//设置代理类型
            const int INTERNET_OPEN_TYPE_PROXY = 3;

//设置代理类型,直接访问,不需要通过代理服务器了

const int INTERNET_OPEN_TYPE_DIRECT = 1;

Struct_INTERNET_PROXY_INFO struct_IPI;
            // Filling in structure 
            struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY;

//把代理地址设置到非托管内存地址中 
            struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy);

//代理通过本地连接到代理服务器上
            struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local");

// Allocating memory

//关联到内存
            IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI));
            if (string.IsNullOrEmpty(strProxy) || strProxy.Trim().Length == 0)
            {
                strProxy = string.Empty;
                struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_DIRECT;
            }

// Converting structure to IntPtr

//把结构体转换到句柄
            Marshal.StructureToPtr(struct_IPI, intptrStruct, true);
            bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI));
        }

private void button1_Click(object sender, EventArgs e)
        {
                InternetSetOption("192.168.6.218:3128");

webBrowser1.Navigate("http://www.baidu.com", null, null, null);
        }

上面是代码是设置代理,要是取消代理怎么实现?

很简单,把调用InternetSetOption(string strProxy) 函数中的strProxy参数设置为空就行了。

例如:

private void button2_Click(object sender, EventArgs e)
        {
                InternetSetOption(string.Empty);

webBrowser1.Navigate("http://www.baidu.com", null, null, null);
        }