ModelingDebug/ProxySettingsHelper.cs

77 lines
2.7 KiB
C#
Raw Normal View History

using Debug.MODS;
using Microsoft.Win32;
using System.Runtime.InteropServices;
namespace Debug;
#pragma warning disable CA1416 // 验证平台兼容性
#pragma warning disable CS8600 // 将 null 字面量或可能为 null 的值转换为非 null 类型。
public class ProxySettingsHelper : Activity
{
public const string Title = "服务器代理";
// 引入WinINet API函数
[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
private const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
private const int INTERNET_OPTION_REFRESH = 37;
public string? proxy = "127.0.0.1:7890"; // 代理服务器地址
public bool enableProxy = false; // true 开启代理false 关闭代理
public ProxySettingsHelper(object class_)
{
enableProxy = IsProxyEnabled();
_ = new ModeSwitch(class_, "Proxy设置", ["关闭代理", "打开代理"], (a) =>
{
switch (a)
{
case 0:
SetProxy(false, proxy);
break;
case 1:
SetProxy(true, proxy);
break;
}
_ = new ProxySettingsHelper(class_);
}, $"代理已{(enableProxy ? "" : "")},地址: {proxy}");
}
public void SetProxy(bool enable, string proxyAddress)
{
string proxyEnable = enable ? "1" : "0";
string proxyServer = enable ? proxyAddress : "";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true))
{
if (key != null)
{
key.SetValue("ProxyEnable", proxyEnable, RegistryValueKind.DWord);
key.SetValue("ProxyServer", proxyServer, RegistryValueKind.String);
}
}
// 使更改立即生效
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
}
public bool IsProxyEnabled()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", false))
{
if (key == null) return false;
object proxyEnable = key.GetValue("ProxyEnable");
object proxyServer = key.GetValue("ProxyServer");
bool enabled = proxyEnable != null && (int)proxyEnable == 1;
if (enabled && proxyServer != null && proxyServer.ToString() != null)
{
proxy = proxyServer?.ToString();
}
return enabled;
}
}
}