苏飞论坛

标题: C#webBrowser使用代理服务器的方法winform [打印本页]

作者: 站长苏飞    时间: 2013-3-29 13:16
标题: C#webBrowser使用代理服务器的方法winform
                           C#webBrowser使用代理服务器的方法winform
   其实在C#中使用webBrowser大家应该都会了,论坛也有很多相前的例子大家可以查询一下就知道了
但是像直接使用浏览器一样设置代理 的方法可能很多人还不知道吧。
这个其实是调用一个Dll文件进行设置的,
下面大家跟我一起来看看吧
首先还是要先建一个结构就是代理信息的结构体
如下
[C#] 纯文本查看 复制代码
 /// <summary>
    /// 代理结构体
    /// </summary>
    public struct Struct_INTERNET_PROXY_INFO
    {
        public int dwAccessType;
        public IntPtr proxy;//IP以及端口号
        public IntPtr proxyBypass;
    };

下面是如何 设置代理 的具体实现
[C#] 纯文本查看 复制代码
/// <summary>
        /// 设置代理的Api
        /// </summary>
        /// <returns></returns>
        [DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);

        /// <summary>
        /// 代理IP以及端口号
        /// </summary>
        /// <param name="strProxy"></param>
        private void RefreshIESettings(string strProxy)
        {
            const int INTERNET_OPTION_PROXY = 38;
            const int INTERNET_OPEN_TYPE_PROXY = 3;

            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));

            // Converting structure to IntPtr
            Marshal.StructureToPtr(struct_IPI, intptrStruct, true);

            bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, Marshal.SizeOf(struct_IPI));
        }[

使用的时候也非常的简单
[C#] 纯文本查看 复制代码
RefreshIESettings("41.129.53.227:80");
                webBrowser1.Navigate("http://www.sufeinet.com");

这样就可以了。
好了大家自己试试吧。

作者: W@lf    时间: 2013-9-3 10:01
如果代理需要用户名和密码呢?
作者: 天山明月    时间: 2013-9-11 10:58
刚才测了下,页面没有打开,并且页面的url变成res://ieframe.dll/dnserrordiagoff_webOC.htm#测试的Url


这是什么 情况 ?


作者: wetpffxoq    时间: 2013-9-17 04:27
鼓励一下,帖子非常好
作者: dingon    时间: 2014-5-5 23:19
不起作用 是什么原因?
作者: ching126    时间: 2014-9-9 23:00
强烈支持楼主ing……
作者: 709397563    时间: 2019-11-29 00:51
请问楼主,怎么知道设置的代理成功了呢?
作者: futiem    时间: 2020-1-4 10:49
webBrowser使用代理服务器的方法winform




欢迎光临 苏飞论坛 (http://www.sufeinet.com/) Powered by Discuz! X3.4