3

I have to make application that will connect/disconnect to proxy server even while browser is running. I found out that I can change some registry keys value. Here is my code in 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

This code works well on Firefox, but doesn't on IE and Chrome. While IE is opened it prevents all registry changes in Internet Settings. Chrome needs restart or opening the Proxy settings to reload proxy information. How to force browers to reload proxy configuration?

EDIT Example: ChrisProxy

4

2 回答 2

1

You can utilize WebClient to connect and set a proxy. A very simple example is shown below.

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
于 2012-12-26T16:51:14.643 回答
1

You should call, in your program:

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.

With that code, no need to restart or opening the proxy settings to reload proxy information. Existing Chrome and Internet Explorer instances are notified by INTERNET_OPTION_SETTINGS_CHANGED and INTERNET_OPTION_REFRESH.


Notes:

  1. Your calling program can't be a service. InternetSetOption() is a WinINet call.
  2. It should run under the same-user (as of the browser) account.
于 2014-11-26T14:57:21.093 回答