我必须制作即使在浏览器运行时也能连接/断开到代理服务器的应用程序。我发现我可以更改一些注册表项值。 这是我在 Visual Basic 中的代码:
Imports Microsoft.Win32
Public Class Form1
Public Sub SetProxy()
On Error Resume Next
Dim regkey1 As RegistryKey
regkey1 = Registry.CurrentUser.CreateSubKey("Software\Microsoft\Windows\CurrentVersion\Internet Settings", RegistryKeyPermissionCheck.Default)
regkey1.SetValue("ProxyServer", "ftp=10.8.0.1:808;http=10.8.0.1:808;https=10.8.0.1:808;socks=10.8.0.1:1080", RegistryValueKind.Unknown)
regkey1.SetValue("ProxyEnable", True, RegistryValueKind.DWord)
regkey1.Close()
Label1.Text = "Connected to Disa's Proxy Server"
Label1.ForeColor = Color.Green
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
On Error Resume Next
SetProxy()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
On Error Resume Next
Dim regKey As RegistryKey
regKey = Registry.CurrentUser.CreateSubKey("Software\Microsoft\Windows\CurrentVersion\Internet Settings", RegistryKeyPermissionCheck.Default)
regKey.SetValue("ProxyEnable", False, RegistryValueKind.DWord)
regKey.Close()
Label1.Text = "Disconnected from Disa's Proxy Server"
Label1.ForeColor = Color.Red
End Sub
End Class
此代码在 Firefox 上运行良好,但在 IE 和 Chrome 上不起作用。 当 IE 打开时,它会阻止
Internet Settings
中的所有注册表更改。 Chrome 需要重新启动或打开代理设置才能重新加载代理信息。
如何强制浏览器重新加载代理配置?
编辑 示例:ChrisProxy
你应该在你的程序中调用:
InternetSetOption(NULL, INTERNET_OPTION_SETTINGS_CHANGED, NULL, 0);
// Notifies the system that the registry settings have been changed
// so that it verifies the settings on the next call to InternetConnect.
InternetSetOption(NULL, INTERNET_OPTION_REFRESH , NULL, 0);
// Causes the proxy data to be reread from the registry for a handle.
// No buffer is required.
使用该代码,无需重新启动或打开代理设置即可重新加载代理信息。 INTERNET_OPTION_SETTINGS_CHANGED 和 INTERNET_OPTION_REFRESH 会通知现有 Chrome 和 Internet Explorer 实例。
备注:
您可以利用WebClient连接并设置代理。下面显示了一个非常简单的示例。
Sub GetWebPageWithProxy(ByVal pathToUrl As String, ByVal pathToSaveFile As String)
Dim wc As WebClient
wc = New WebClient
wc.Proxy = New WebProxy(New Uri("http://10.8.0.1:808"))
wc.DownloadFile(pathToUrl, pathToSaveFile)
End Sub
InternetSetOption(NULL, INTERNET_OPTION_SETTINGS_CHANGED, NULL, 0);
// Notifies the system that the registry settings have been changed
// so that it verifies the settings on the next call to InternetConnect.
InternetSetOption(NULL, INTERNET_OPTION_REFRESH , NULL, 0);
// Causes the proxy data to be reread from the registry for a handle.
// No buffer is required.
我不知道为什么这在 Windows 10 中不起作用,每次我在 HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings 中设置值 AutoConfigURL 时,我需要重新启动浏览器才能使其工作。