-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
105 lines (96 loc) · 3.3 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Drawing;
using System.Management;
using System.Security.Principal;
using System.Windows.Forms;
namespace ProxyTray
{
internal static class Program
{
const string KeyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
static readonly string StatusChangeEventQuery = (
"SELECT * FROM RegistryValueChangeEvent WHERE " +
$"Hive = 'HKEY_USERS' AND KeyPath = '{WindowsIdentity.GetCurrent().User.Value}\\{KeyPath}' " +
"AND (ValueName = 'ProxyEnable' or ValueName = 'ProxyServer')"
).Replace(@"\", @"\\");
const string None = "<None>";
static Icon ProxyOnIcon;
static Icon ProxyOffIcon;
static NotifyIcon Tray;
static bool ProxyEnable;
static string ProxyServer;
static void Initialize()
{
ProxyOnIcon = new Icon("ProxyOn.ico");
ProxyOffIcon = new Icon("ProxyOff.ico");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
}
static void CreateTray()
{
var settingItem = new MenuItem
{
Index = 0,
Text = "Proxy Setting"
};
settingItem.Click += (sender, e) => Process.Start("ms-settings:network-proxy");
var menuItem = new MenuItem
{
Index = 1,
Text = "Quit"
};
menuItem.Click += (sender, e) => Application.Exit();
Tray = new NotifyIcon
{
ContextMenu = new ContextMenu(new[] { settingItem, menuItem }),
Visible = true
};
Tray.MouseClick += (sender, e) =>
{
if (e.Button != MouseButtons.Left) return;
if (ProxyServer == None)
{
MessageBox.Show("'ProxyServer' not configured");
Process.Start("ms-settings:network-proxy");
return;
}
using (var key = Registry.CurrentUser.OpenSubKey(KeyPath, true))
{
key.SetValue("ProxyEnable", ProxyEnable ? 0 : 1);
}
};
}
static void RefreshTray()
{
using (var key = Registry.CurrentUser.OpenSubKey(KeyPath))
{
ProxyEnable = (int)(key.GetValue("ProxyEnable", 0)) != 0;
ProxyServer = (string)(key.GetValue("ProxyServer", None));
}
Tray.Icon = ProxyEnable ? ProxyOnIcon : ProxyOffIcon;
Tray.Text = ProxyEnable ? ProxyServer : "Direct";
}
[STAThread]
static void Main()
{
try
{
Initialize();
CreateTray();
RefreshTray();
using (var watcher = new ManagementEventWatcher(StatusChangeEventQuery))
{
watcher.EventArrived += (sender, e) => RefreshTray();
watcher.Start();
Application.Run();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}