C#设置IE代理及遇到问题的解决方案
起初使用的方法是修改完一次代理之后就不能继续修改,需要重新启动一次进程才可以,最初代码是:
private void ShowProxyInfo()
{
if (!GetProxyStatus())
{
lblInitInfo.Text = "代理未启用:";
}
else
{
lblInitInfo.Text = "当前使用的代理是:" + GetProxyServer();
} } private void InitProxyData()
{
List<string> proxyList = new List<string>{
"http://web-proxy.cup.hp.com:8080","http://proxy.compaq.com:8080"
};
combProxyList.DataSource = proxyList;
combProxyList.SelectedIndex = ;
}
public void SetProxy(string proxy)
{
//打开注册表
//RegistryKey regKey = Registry.CurrentUser;
//string SubKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
//RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true); //更改健值,设置代理,
//optionKey.SetValue("ProxyEnable", 1);
//optionKey.SetValue("ProxyServer", proxy); ////激活代理设置【用于即使IE没有关闭也能更新当前打开的IE中的代理设置。】
//InternetSetOption(0, 39, IntPtr.Zero, 0);
//InternetSetOption(0, 37, IntPtr.Zero, 0);
//regKey.Flush(); //刷新注册表
//regKey.Close();
//ShowProxyInfo(); using (RegistryKey regKey = Registry.CurrentUser)
{
string SubKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true); //更改健值,设置代理
optionKey.SetValue("ProxyEnable", );
optionKey.SetValue("ProxyServer", proxy);
//激活代理设置【用于即使IE没有关闭也能更新当前打开的IE中的代理设置。】
InternetSetOption(, , IntPtr.Zero, );
InternetSetOption(, , IntPtr.Zero, );
regKey.Flush(); //刷新注册表
ShowProxyInfo();
} } public void DisableProxy()
{
//打开注册表
RegistryKey regKey = Registry.CurrentUser;
string SubKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true); //更改健值,设置代理,
optionKey.SetValue("ProxyEnable", );
regKey.Flush(); //刷新注册表
InternetSetOption(, , IntPtr.Zero, );
InternetSetOption(, , IntPtr.Zero, );
regKey.Close();
ShowProxyInfo();
} [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); private void btnSetProxy_Click(object sender, EventArgs e)
{
string proxyStr = combProxyList.Text.Trim();
SetProxy(proxyStr);
var currentProxy = GetProxyServer();
if (currentProxy == proxyStr && GetProxyStatus())
{
lblInfo.Text = "设置代理:" + proxyStr + "成功!";
lblInfo.ForeColor = Color.Green;
}
else
{
if (!GetProxyStatus())
{
lblInfo.Text = "设置代理:" + proxyStr + "代理未启用!"; }
else
{
lblInfo.Text = "设置代理:" + proxyStr + "失败,正在使用" + currentProxy + "代理,请重试!"; }
lblInfo.ForeColor = Color.Red;
}
ShowProxyInfo(); } /// <summary>
/// 获取正在使用的代理
/// </summary>
/// <returns></returns>
private string GetProxyServer()
{
//打开注册表
RegistryKey regKey = Registry.CurrentUser;
string SubKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true); //更改健值,设置代理,
string actualProxy = optionKey.GetValue("ProxyServer").ToString();
regKey.Close();
return actualProxy;
} private bool GetProxyStatus()
{
//打开注册表
RegistryKey regKey = Registry.CurrentUser;
string SubKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true); //更改健值,设置代理,
int actualProxyStatus = Convert.ToInt32(optionKey.GetValue("ProxyEnable"));
regKey.Close();
return actualProxyStatus == ? true : false;
} //成功返回true,错误返回false
public Boolean prcessBaidu()
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.163.com");
myRequest.Method = "POST"; //采用post方式提交访问163主页 // Get response
try//当无法访问163网站时,下面的对象会有错误产生,所以用try..catch处理掉这些异常
{
Stream newStream = myRequest.GetRequestStream();//获取请求流 // Send the data.
newStream.Close();//关闭请求流
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();//获取应答对象
StreamReader reader = new StreamReader(myResponse.GetResponseStream());//获取应答流
string content = reader.ReadToEnd();//将流对象读取到string 中
if (content.IndexOf("http://reg.163.com") > -)//如果访问网站成功,则网页中包含置顶的关键字符串“http://reg.163.com”表示访问网页成功
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
return false;
} private void btnDisableProxy_Click(object sender, EventArgs e)
{
DisableProxy(); if (!GetProxyStatus())
{
lblInfo.Text = "取消代理完成!";
lblInfo.ForeColor = Color.Green;
}
else
{
lblInfo.Text = "取消失败,正在使用代理" + GetProxyServer();
lblInfo.ForeColor = Color.Red;
}
ShowProxyInfo();
} private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{ } private void btnTestProxy_Click(object sender, EventArgs e)
{
string proxyStr = combProxyList.SelectedText;
SetProxy(proxyStr);
if (prcessBaidu())
{
MessageBox.Show("代理可以正常访问。");
}
else
{
MessageBox.Show("目前无法使用代理!");
}
ShowProxyInfo();
}
有网友的结果是说在window7下, 在一个进程中, 设置和取消不能都执行,---- 要么设置,要么取消。 但如果第一次运行时,只进行设置代理,退出后再进运行,只进行取消,这是没有问题的。简单说说他给出的解决方案:每次设置或取消代理时,都新建一个进程,在新的进程中处理,处理完之后关掉进程。参考http://blog.csdn.net/debug__boy/article/details/8432879提供新的解决方案,国外大神的文章http://huddledmasses.org/setting-windows-internet-connection-proxy-from-c/:代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks; namespace IEProxyManagment
{ public class IEProxySetting
{
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) ? : (string.IsNullOrEmpty(exceptions) ? : );
InternetConnectionOption[] options = new InternetConnectionOption[optionCount];
// USE a proxy server ...
options[].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
options[].m_Value.m_Int = (int)((optionCount < ) ? PerConnFlags.PROXY_TYPE_DIRECT : (PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY));
// use THIS proxy server
if (optionCount > )
{
options[].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER;
options[].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(strProxy);
// except for these addresses ...
if (optionCount > )
{
options[].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPASS;
options[].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(exceptions);
}
} // default stuff
list.dwSize = Marshal.SizeOf(list);
list.szConnection = IntPtr.Zero;
list.dwOptionCount = options.Length;
list.dwOptionError = ; 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 = ; 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 list
IntPtr 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) ? - : ;
if (returnvalue == )
{ // get the error codes, they might be helpful
returnvalue = Marshal.GetLastWin32Error();
}
// FREE the data ASAP
Marshal.FreeCoTaskMem(optionsPtr);
Marshal.FreeCoTaskMem(ipcoListPtr);
if (returnvalue > )
{ // throw the error codes, they might be helpful
throw new Win32Exception(Marshal.GetLastWin32Error());
} return (returnvalue < );
}
} #region WinInet structures
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct InternetPerConnOptionList
{
public int dwSize; // size of the INTERNET_PER_CONN_OPTION_LIST struct
public IntPtr szConnection; // connection name to set/query options
public int dwOptionCount; // number of options to set/query
public 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()]
public System.Runtime.InteropServices.ComTypes.FILETIME m_FileTime;
[FieldOffset()]
public int m_Int;
[FieldOffset()]
public IntPtr m_StringPtr;
}
}
#endregion #region WinInet enums
//
// options manifests for Internet{Query|Set}Option
//
public enum InternetOption : uint
{
INTERNET_OPTION_PER_CONNECTION_OPTION =
} //
// Options used in INTERNET_PER_CONN_OPTON struct
//
public enum PerConnOption
{
INTERNET_PER_CONN_FLAGS = , // Sets or retrieves the connection type. The Value member will contain one or more of the values from PerConnFlags
INTERNET_PER_CONN_PROXY_SERVER = , // Sets or retrieves a string containing the proxy servers.
INTERNET_PER_CONN_PROXY_BYPASS = , // Sets or retrieves a string containing the URLs that do not use the proxy server.
INTERNET_PER_CONN_AUTOCONFIG_URL = //, // 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 net
PROXY_TYPE_PROXY = 0x00000002, // via named proxy
PROXY_TYPE_AUTO_PROXY_URL = 0x00000004, // autoproxy URL
PROXY_TYPE_AUTO_DETECT = 0x00000008 // use autoproxy detection
}
#endregion internal 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);
}
}
UnsetProxy方法为取消代理设置,SetProxy(string strProxy, string exceptions)方法为设置指定代理。
以下是我做的一个可以动态修改代理的Winform程序,备忘下载。
C#设置IE代理及遇到问题的解决方案的更多相关文章
- C#设置通过代理访问ftp服务器
// 创建FTP连接 private FtpWebRequest CreateFtpWebRequest(string uri, string requestMethod) { FtpWebReque ...
- atitit agt sys 设置下级代理功能设计.docx
atitit agt sys 设置下级代理功能设计.docx 显示界面1 先查询显示 set_sub.js1 设置代理2 /atiplat_cms/src/com/attilax/user/Agent ...
- Nginx_地址重写(rewrite)_日志管理(log_format)_压缩输出_Nginx设定限速_Nginx设置反向代理及反向代理缓存
Nginx地址重写 Nginx rewrite rewrite语法规则1).变量名可以使用 "=" 或 "!=" 运算符~ 区分大小写~* 不区分大小写^~ 禁 ...
- maven3实战之设置HTTP代理
maven3实战之设置HTTP代理 ---------- 有时候你所在的公司基于安全因素考虑,要求你使用通过安全认证的代理访问因特网.这种情况下,就需要为Maven配置HTTP代理,才能让它正常访问外 ...
- 快捷设置IE代理小工具
时间:2015-02-06 起因: 公司新装了PLM系统,用这个系统必须使用指定IP段的IP才能访问.所以为了还能愉快的继续使用代理进行特定网站的访问,我们必须要频繁的去设置IE代理,这也太麻烦了吧. ...
- 设置HTTP代理
Maven通过<<UserHome>>/.m2/settings.xml(如果没有该文件,复制<<MavenHome>>/conf/settings.x ...
- 在cocos2d-x jsb/html5中设置触摸代理的方法
和官方的说明不同,js binding的很多api和ch5版是不一样的.遇到不一样的就需要我们努力去看源码寻找了. 主要是以下几个文件 cocos2d_specifics.cpp cocos2d_sp ...
- 转:设置HtmlUnitDriver代理及处理用户验证有关问题
selenium2 提供了一种无ui模式的driver,即htmlunitdriver.特点运行比较快.其实htmlunitdriver 是对htmlunit 的封装,这样大家就可以使用自己习惯sel ...
- 主机设置ss代理,虚拟机共享代理
代理的原理: 关于代理的具体的书面定义你百度谷歌可以知道.这里,我想简单通过一个例子,说明代理的原理: 假如,你在北京,但你女朋友在广州,你有东西要给你的女朋友,但是正好你这几天公司有事,所以你不能去 ...
随机推荐
- CSS3 速移动效果动画流畅无卡顿
js或jquery 元素移动以像素计算,手机上移动效果会有卡顿 利用CSS3 可以很简单的实现流畅的移动动画 transform: translate3d(66px, 88px, 0px) rotat ...
- 利用AOP与ToStringBuilder简化日志记录
刚学spring的时候书上就强调spring的核心就是ioc和aop blablabla...... IOC到处都能看到...AOP么刚开始接触的时候使用在声明式事务上面..当时书上还提到一个用到ao ...
- 【转载】在IT界取得成功应该知道的10件事
在IT界取得成功应该知道的10件事 2011-08-11 13:31:30 分类: 项目管理 导读:前面大多数文章都是Jack Wallen写的,这是他的新作,看来要成为NB程序员还要不停的自我总结 ...
- svn 版本迁移到 git 仓库
1.拉取 svn代码并转成 git 版本 git svn fetch http://svn.qtz.com/svn/qtz_code/java/qtz_sm/project/qtz_sm -Auser ...
- 在sql语句中使用 xml for path 格式化字符串的方法总结
此方法实现的是将查询表中的某个字段,格式化成 字符串1,字符串2,字符串3...的格式 假设我们现在有两个表 分别是 分组表 grouped和分组成员表 groupuser grouped表有连个字 ...
- GSM07.10协议中串口复用的注意事项
DLCI:0通道(地址域中DLCI==0)是控制通道,用来传输管理信息.逻辑通道的建立和关闭,睡眠模式的启动和唤醒,流量控制等控制信息都是用该通道. DLCI:1~n通道是逻辑通道,用来传输用户数据. ...
- 查找Linux中内存和CPU使用率最高的进程
下面的命令会查看到按照RAM和CPU降序方式的前最高几名进程的列表: [root@iZ25pvjcsyhZ ~]# ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem ...
- 耿丹CS16-2班第五次作业汇总
Deadline: 2016-10-26 23:59 作业内容 实验4-1 求1到20的阶乘的和,其中求阶乘用函数完成. 实验4-2 写一个判素数的函数,在主函数输入一个整数,输出其是否是素数的信息. ...
- ajax简单应用
var xmlhttp;if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码 xmlhttp=new ...
- Unhandled Exception:System.DllNotFoundException: Unable to load DLL"**":找不到指定的模块
在项目中使用C#代码调用C++ DLL时.常常会出现这个问题:在开发者自己的电脑上运行没有问题,但是部署到客户电脑上时会出现下面问题: Unhandled Exception:System.DllNo ...