I am trying to enable / disable the Windows global proxy (on the Internet) using the Windows registry. If I set the value, I have no problem but updating the settings. After searching, I found a question about SO that provided code for this. But now the problem is that it only works once per application session. that is, it works for the first time, and if you want it to work again, you need to restart the application. Any ideas what could be the problem ??? here is the code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;
namespace SystemProxyToggle
{
public partial class Form1 : Form
{
[DllImport("wininet.dll")]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
public const int INTERNET_OPTION_REFRESH = 37;
static bool settingsReturn, refreshReturn;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
queryStatus();
}
private void btnToggle_Click(object sender, EventArgs e)
{
toggleStatus();
queryStatus();
}
private void queryStatus()
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
int status = (int)registry.GetValue("ProxyEnable");
if (status == 0)
{
lblStatus.Text = "Proxy Is Disabled";
lblStatus.ForeColor = Color.Maroon;
}
else
{
lblStatus.Text = "Proxy Is Enabled";
lblStatus.ForeColor = Color.Green;
}
registry.Close();
}
private void toggleStatus()
{
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
int status = (int)registry.GetValue("ProxyEnable");
if (status == 1)
{
registry.SetValue("ProxyEnable", 0);
}
else
{
registry.SetValue("ProxyEnable", 1);
}
settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
registry.Close();
}
}
}
source
share