C# WebBrowser İle Proxy Kullanımı
Visual studio ile c# kendi apisini kullanarak WebBroseri proxy ile çalıştırmanın kesin ve sağlıklı bir yolu yoktur , fakat bu aşağıdaki 2 yöntem hiç yoktan işinizi görebilecek kadar etkilidir.
1. Yöntem (Kayıt defterinden IE nin proxysini değiştirmek)
Bu yöntem ile kayıt defterinden Web Browserin tabanı olan Internet Explorerin proxysini değiştirirsiniz , bu sayede arayüz içerisinden rahatlıkla proxy ile bağlantı kurarsınız.
Form.Load içerisine bu kodu yapıştırıp deneyebilirsiniz.. Her navigate'de bu işlemi yapmanıza gerek yok bir kere set ettinizmi değiştirene kadar o proxyden işlem görür webbrowser.
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", "http://proxy:port");
webBrowser1.Navigate("URL");
2. Yöntem (wininet.dll kullanarak değiştirmek)
Bu yöntem ile wininet.dll kullanılarak IE'yi etkliemeden proxy eklersiniz.
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test_Proxy
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption,
IntPtr lpBuffer, int lpdwBufferLength);
private Guid IID_IAuthenticate = new Guid("79eac9d0-baf9-11ce-8c82-00aa004ba90b");
private const int INET_E_DEFAULT_ACTION = unchecked((int)0x800C0011);
private const int S_OK = unchecked((int)0x00000000);
private const int INTERNET_OPTION_PROXY = 38;
private const int INTERNET_OPEN_TYPE_DIRECT = 1;
private const int INTERNET_OPEN_TYPE_PROXY = 3;
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ScriptErrorsSuppressed = true;
}
private void button1_Click(object sender, EventArgs e)
{
SetProxyServer("http://proxy:port");
webBrowser1.Navigate("URL");
}
public struct INTERNET_PROXY_INFO
{
public int dwAccessType;
public IntPtr proxy;
public IntPtr proxyBypass;
}
private void SetProxyServer(string proxy)
{
//Create structure
INTERNET_PROXY_INFO proxyInfo = new INTERNET_PROXY_INFO();
if (proxy == null)
{
proxyInfo.dwAccessType = INTERNET_OPEN_TYPE_DIRECT;
}
else
{
proxyInfo.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
proxyInfo.proxy = Marshal.StringToHGlobalAnsi(proxy);
proxyInfo.proxyBypass = Marshal.StringToHGlobalAnsi("local");
}
// Allocate memory
IntPtr proxyInfoPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(proxyInfo));
// Convert structure to IntPtr
Marshal.StructureToPtr(proxyInfo, proxyInfoPtr, true);
bool returnValue = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY,
proxyInfoPtr, Marshal.SizeOf(proxyInfo));
}
}
}
Yorumlar
Yorum Gönder