Search code examples
visual-studioproxyregistry

Proxy connection while browser is running


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


Solution

  • 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.