在《VB设置WebBrowser的COOKIE、临时文件夹等路径》一文中,我们介绍了为Webbrowser设置cookie路径的方法,同理可以为Webbrowser设置代理。但是如果程序中没有Webbrowser控件,用到了其他的网络功能,怎么设置代理呢?我们可以调用wininet.dll中的InternetSetOption函数。好了,直接给出核心代码。
'========================================
'声明作用:为本实例设置代理
'========================================
Private Const INTERNET_OPTION_PROXY = 38
Private Const URLMON_OPTION_USERAGENT = &H10000001
Private Const INTERNET_OPEN_TYPE_PROXY = 3
Private Const INTERNET_OPTION_SETTINGS_CHANGED = 39
Private Declare Sub UrlMkSetSessionOption Lib "urlmon.dll" (ByVal dwOption As Long, pbuffer As Any, ByVal dwBufferLength As Long, ByVal dwreserved As Long)
Private Type INTERNET_PROXY_INFO
dwAccessType As Long
lpszProxy As String
lpszProxyBypass As String
End Type
Private Declare Function InternetSetOption Lib "wininet.dll" _
Alias "InternetSetOptionA" _
(ByVal hInternet As Long, _
ByVal dwOption As Long, _
ByRef lpBuffer As Any, _
ByVal dwBufferLength As Long) As Long
'========================================
'函数名称:SetProxy
'函数作用:为本实例设置代理
'函数参数:比如SOCKS=127.0.0.1:1987
'========================================
Public Function SetProxy(ByVal Proxy As String)
Dim options As INTERNET_PROXY_INFO
options.dwAccessType = INTERNET_OPEN_TYPE_PROXY
options.lpszProxy = Proxy
options.lpszProxyBypass = ""
InternetSetOption 0, INTERNET_OPTION_PROXY, options, LenB(options)
InternetSetOption INTERNET_OPTION_SETTINGS_CHANGED, 0, 0, 0
End Function