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