SetProxy

2016-06-23

I wanted to switch the Internet Proxy in windows automatically when a selected network interfaces went Up or Down. Currently this is a manual action. This program I developed in Visual Studio 2015 C# is doing this automatically.

Main program:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using System.Security.AccessControl;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;


namespace SetProxy
{
 public partial class Form1 : Form
 {
 public Form1()
 {
 InitializeComponent();
 }

 private void Form1_Load(object sender, EventArgs e)
 {
 NetworkChange.NetworkAddressChanged += new
 NetworkAddressChangedEventHandler(AddressChangedCallback);

 toolStripStatusLabel1.Margin = new System.Windows.Forms.Padding(3, 0, 350, 0);

 toolStripStatusLabel2.Text = "Version 2 (c)pa1kw";
 this.Invoke(new EventHandler(DisplayText));

 }

 public void AddressChangedCallback(object sender, EventArgs e)
 {
 this.Invoke(new EventHandler(DisplayText));
 
 }

 private void DisplayText(object sender, EventArgs e)
 {
 DateTime logDate = DateTime.Now;
 textBox1.AppendText("-------------------------------" + "\n");
 textBox1.AppendText(logDate.ToString() + "\n");
 textBox1.AppendText("-------------------------------" + "\n");


 NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

 checkedListBox1.Items.Clear();

 int proxy_count = 0;

 foreach (NetworkInterface n in adapters)
 {
 textBox1.AppendText(n.Name + " - " + n.OperationalStatus + "\n");
 int i = checkedListBox1.Items.Add(n.Name);
 
 if (Config.CheckConfig(n.Name)) {
 checkedListBox1.SetItemChecked(i, true);
 //if interface is checked and Up
 if (n.OperationalStatus == OperationalStatus.Up)
 {
 proxy_count++;
 }
 
 }
 }
 
 if (proxy_count == 0)
 {
 Regkey.set_regkey_proxystatus(0);
 }
 else
 {
 Regkey.set_regkey_proxystatus(1);
 }

 textBox2.Text =Regkey.get_regkey_proxyurl();

 if (Regkey.get_regkey_proxystatus() == 1 )
 {
 textBox1.AppendText("Proxy: " + Regkey.get_regkey_proxyurl() + "\n");
 toolStripStatusLabel1.Text = "Proxy is On ";
 }
 else
 {
 textBox1.AppendText("Proxy is null; no proxy will be used \n");
 toolStripStatusLabel1.Text= "Proxy is Off";
 }
 }

 private void button1_Click(object sender, EventArgs e)
 {
 //Get Status button
 this.Invoke(new EventHandler(DisplayText));
 }

 private void button2_Click(object sender, EventArgs e)
 {
 //Exit button click
 if (System.Windows.Forms.Application.MessageLoop)
 {
 // Use this since we are a WinForms app
 System.Windows.Forms.Application.Exit();
 }
 else
 {
 // Use this since we are a console app
 System.Environment.Exit(1);
 }
 }

 private void button3_Click(object sender, EventArgs e)
 {
 //Proxy button
 if (Regkey.get_regkey_proxystatus() == 0) 
 {
 Regkey.set_regkey_proxystatus(1);
 }
 else
 {
 Regkey.set_regkey_proxystatus(0);
 }
 this.Invoke(new EventHandler(DisplayText));
 }

 private void button4_Click(object sender, EventArgs e)
 {
 //Save proxy address button
 Regkey.set_regkey_proxyurl(textBox2.Text.ToString());
 }

 private void Form1_Resize(object sender, EventArgs e)
 {
 //if the form is minimized 
 //hide it from the task bar 
 //and show the system tray icon (represented by the NotifyIcon control) 
 if (this.WindowState == FormWindowState.Minimized)
 {
 Hide();
 notifyIcon1.Visible = true;
 }
 }

 private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
 {
 Show();
 this.WindowState = FormWindowState.Normal;
 notifyIcon1.Visible = false;
 }

 private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
 {

 int i = checkedListBox1.SelectedIndex;
 if (i != -1)
 {
 if (!checkedListBox1.GetItemChecked(i))
 {
 textBox1.AppendText("Add config :" + checkedListBox1.SelectedItem.ToString() + "\n");
 Config.AddUpdateAppSettings(checkedListBox1.SelectedItem.ToString(), "1");

 }
 else
 {
 
 textBox1.AppendText("Remove config :" + checkedListBox1.SelectedItem.ToString() + "\n");
 Config.deleteAppSetting(checkedListBox1.SelectedItem.ToString(), "1");
 }
 }
 }

 private void checkBox1_CheckedChanged(object sender, EventArgs e)
 {
 //Start minimized on Windows Startup
 if (checkBox1.Checked) {
 Config.AddUpdateAppSettings("StartMinimized", "1");
 }
 else
 {
 Config.AddUpdateAppSettings("StartMinimized", "0");
 }
 }

 private void Form1_Shown(object sender, EventArgs e)
 {

 //if Start minimized on Windows Startup is enabled
 if (Config.CheckConfig("StartMinimized"))
 {
 if (Config.ReadSetting("StartMinimized") == "1")
 {

 this.WindowState = FormWindowState.Minimized;
 this.Hide();
 notifyIcon1.Visible = true;
 checkBox1.Checked = true;
 }
 }
 }
 }
}

RegKey Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;


namespace SetProxy
{
    public class Regkey
    {
        //RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);

        public static void set_regkey_proxystatus(int set)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            if (set == 0)
            {
                key.SetValue("ProxyEnable", 0);
            }
            else
            {
                key.SetValue("ProxyEnable", 1);
            }
        }

        public static void set_regkey_proxyurl(string set)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
            key.SetValue("ProxyServer", set);
        }


        public static int get_regkey_proxystatus()
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings");
            return (int)key.GetValue("ProxyEnable");
        }

        public static string get_regkey_proxyurl()
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings");
            return (string)key.GetValue("ProxyServer");
        }


    }
}

Config Class:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;


namespace SetProxy
{
    public class Config
    {

        public static int CountConfig()
        {
            try
            {
                var appSettings = ConfigurationManager.AppSettings;

                return appSettings.Count;
                
            }
            catch (ConfigurationErrorsException)
            {
                return 0;
            }
        }

        public static bool CheckConfig(string key)
        {
            try
            {
                var appSettings = ConfigurationManager.AppSettings;
                if (appSettings[key] == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
                
            }
            catch (ConfigurationErrorsException)
            {
                return false;
            }
        }

        public static string ReadSetting(string key)
        {
            try
            {
                var appSettings = ConfigurationManager.AppSettings;
                return appSettings[key] ?? "Not Found";
                //MessageBox.Show(result);
            }
            catch (ConfigurationErrorsException)
            {
                return ("Error reading app settings");
            }
        }

        public static bool AddUpdateAppSettings(string key, string value)
        {
            try
            {
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = configFile.AppSettings.Settings;
                if (settings[key] == null)
                {
                    settings.Add(key, value);
                }
                else
                {
                    settings[key].Value = value;
                }
                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
                return true;
            }
            catch (ConfigurationErrorsException)
            {
                //MessageBox.Show("Error writing app settings");
                return false;
            }
        }


        public static bool deleteAppSetting(string key, string value)
        {
            try
            {
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = configFile.AppSettings.Settings;
                if (settings[key] == null)
                {
                    //settings.Add(key, value);
                    
                }
                else
                {
                    settings.Remove(key);
                    
                }
                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
                return true;
            }
            catch (ConfigurationErrorsException)
            {
                //MessageBox.Show("Error writing app settings");
                return false;
            }
        }
    
        
    }
}