- using System;
- using System.Collections;
- using System.Threading;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
- using Microsoft.Win32;
- namespace Proxy
- {
- class proxy
- {
- [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "InternetSetOption", CallingConvention = CallingConvention.StdCall)]
- public static extern bool InternetSetOption
- (
- int hInternet,
- int dmOption,
- IntPtr lpBuffer,
- int dwBufferLength
- );
- public static void SetProxy()
- {
- //打开注册表
- RegistryKey regKey = Registry.CurrentUser;
- string SubKeyPath = @"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
- RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
- //更改健值,设置代理,
- if (Convert.ToInt32(optionKey.GetValue("ProxyEnable")) != 1)
- {
- optionKey.SetValue("ProxyEnable", 1);
- //optionKey.SetValue("ProxyServer", proxy);
- Console.WriteLine("Enable Proxy");
- }
- else
- {
- optionKey.SetValue("ProxyEnable", 0);
- //optionKey.SetValue("ProxyServer", proxy);
- Console.WriteLine("Disable Proxy");
- }
- //激活代理设置
- InternetSetOption(0, 39, IntPtr.Zero, 0);
- InternetSetOption(0, 37, IntPtr.Zero, 0);
- }
- public static void SetProxy(string proxy)
- {
- //打开注册表
- RegistryKey regKey = Registry.CurrentUser;
- string SubKeyPath = @"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
- RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
- //更改健值,设置代理,
- if (Convert.ToInt32(optionKey.GetValue("ProxyEnable")) != 1)
- {
- optionKey.SetValue("ProxyEnable", 1);
- optionKey.SetValue("ProxyServer", proxy);
- Console.WriteLine("Enable Proxy");
- }
- else
- {
- optionKey.SetValue("ProxyEnable", 0);
- //optionKey.SetValue("ProxyServer", proxy);
- Console.WriteLine("Disable Proxy");
- }
- //激活代理设置
- InternetSetOption(0, 39, IntPtr.Zero, 0);
- InternetSetOption(0, 37, IntPtr.Zero, 0);
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/2204201512381.html
来源: http://www.codesnippet.cn/detail/2204201512381.html