Introduction
When we are connecting VPN, multiple times, we have to enable disable proxy and change the IP address. For those who want this to happen programmatically, the below code snippet will help.
Background
As a normal process, we use the standard steps given below to change the proxy settings.
Internet Explorer --> Settings --> Internet options --> Connections --> LAN settings
Using the Code
I am bored of opening the internet options every time to change the settings. I started to write code for that and while doing so, I got the interesting information below.
- Registry:
Registry
class helps us to read/write internet proxy settings from code. Using this registry, we can perform modifications on LAN settings. - InternetSetOption
Once we modify the changes, it will not reflect immediately. As process, we have to restart our machine, else we have to use this method to run in the code. It will refresh the settings without restarting the machine.
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ProxyOnOff
{
class Program
{
[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 void Main(string[] args)
{
int a;
bool settingsReturn, refreshReturn;
Console.WriteLine("*************Proxy ON OFF*************\n");
Console.WriteLine("1 for ON\n");
Console.WriteLine("0 for OFF\n");
a= Convert.ToInt32(Console.ReadLine());
RegistryKey registry = Registry.CurrentUser.OpenSubKey
("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
switch (a)
{
case 1:
{
registry.SetValue("ProxyEnable", 1);
registry.SetValue
("ProxyServer", "Your proxy IP:8080");
if ((int)registry.GetValue("ProxyEnable", 0) == 0)
Console.WriteLine("Unable to enable the proxy.");
else
Console.WriteLine("The proxy has been turned on.");
break;
}
case 0:
{
registry.SetValue("ProxyEnable", 0);
registry.SetValue("ProxyServer", 0);
if ((int)registry.GetValue("ProxyEnable", 1) == 1)
Console.WriteLine("Unable to disable the proxy.");
else
Console.WriteLine("The proxy has been turned off.");
break;
}
default:
{
Console.WriteLine("Invalid Argument!");
Console.ReadKey();
return;
}
}
registry.Close();
settingsReturn = InternetSetOption
(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
refreshReturn = InternetSetOption
(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
Console.WriteLine("Press any key to exit...");
}
}
}
To create a program, click on Visual Studio --> New --> Console Application.
In program.cs, paste the above code and publish it.
Points of Interest
This is my first tip on Code Project. I am happy to post it.
History
- 3rd January, 2018: Initial version