-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
463 lines (429 loc) · 16.4 KB
/
MainWindow.xaml.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interop;
namespace RunCat
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private const int CPU_TIMER_DEFAULT_INTERVAL = 3000;
private const int ANIMATE_TIMER_DEFAULT_INTERVAL = 200;
private readonly int MemoryTotleMbytes = Settings.GetPhisicalMemory();
private readonly Settings settings = Settings.ReadSetting();
private readonly Timer animateTimer = new Timer();
private readonly Timer cpuTimer = new Timer();
private PerformanceCounter cpuUsage;
private PerformanceCounter memoryAvailable;
private PerformanceCounter networkTotal = null;
private PerformanceCounter temperatureUsage = null;
//private Hardware hardware = null;
private MenuItem runnerMenu;
private MenuItem themeMenu;
private MenuItem performanceMenu;
private MenuItem startupMenu;
private NotifyIcon notifyIcon;
private int current = 0;
private WindowsTheme systemTheme = ThemeHelper.GetWindowsTheme();
private Icon[] icons;
public MainWindow()
{
InitializeComponent();
Closing += MainWindow_Closing;
}
private void MainWindow_Closing(object sender, CancelEventArgs e)
{
//if (hardware != null) hardware.Dispose();
notifyIcon.Dispose();
}
private string PerformanceInstanceName(string categoryName, string counterName = "")
{
try
{
PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory(categoryName);
if (performanceCounterCategory != null)
{
var instances = performanceCounterCategory.GetInstanceNames();
foreach (string instanceName in instances)
{
foreach (PerformanceCounter counter in performanceCounterCategory.GetCounters(instanceName))
{
if (string.IsNullOrWhiteSpace(counterName) || counter.CounterName.Contains(counterName))
{
return counter.InstanceName;
}
}
}
}
}
catch (Exception)
{
}
return string.Empty;
}
private void Init()
{
cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");
memoryAvailable = new PerformanceCounter("Memory", "Available MBytes");
_ = cpuUsage.NextValue();
_ = memoryAvailable.NextValue();
string networkInstanceName = PerformanceInstanceName("Network Interface", "Bytes Total/sec");//"Bytes Received/sec"
if (!string.IsNullOrWhiteSpace(networkInstanceName))
{
networkTotal = new PerformanceCounter("Network Interface", "Bytes Received/sec", networkInstanceName);
_ = networkTotal.NextValue(); // discards first return value
}
string temperatureInstanceName = PerformanceInstanceName("Thermal Zone Information", "Temperature");
if (!string.IsNullOrWhiteSpace(temperatureInstanceName))
{
temperatureUsage = new PerformanceCounter("Thermal Zone Information", "Temperature", temperatureInstanceName);
_ = temperatureUsage.NextValue(); // discards first return value
}
//else if (Hardware.IsRunAsAdmin())
//{
// hardware = new Hardware();
// if (!hardware.CheckTemperature())
// {
// hardware.Dispose();
// hardware = null;
// }
//}
runnerMenu = new MenuItem(Locale.Runner, new MenuItem[]
{
new MenuItem("Cat", SetRunner)
{
Checked = settings.Runner == RunnerIcon.Cat,
Tag = RunnerIcon.Cat
},
new MenuItem("Parrot", SetRunner)
{
Checked = settings.Runner == RunnerIcon.Parrot,
Tag = RunnerIcon.Parrot
}
});
RunnerIcon instance = new RunnerIcon();
System.Reflection.FieldInfo[] properties = instance.GetType().GetFields();
foreach (System.Reflection.FieldInfo item in properties)
{
string name = item.Name;
if (name == "Cat" || name == "Parrot") continue;
string value = (string)item.GetValue(instance);
runnerMenu.MenuItems.Add(new MenuItem(name, SetRunner)
{
Checked = settings.Runner == value,
Tag = value
});
}
runnerMenu.Popup += RunnerMenu_Popup;
themeMenu = new MenuItem(Locale.Theme, new MenuItem[]
{
new MenuItem(Locale.Default, SetTheme)
{
Checked = settings.CustomTheme == WindowsTheme.Default,
Tag = WindowsTheme.Default
},
new MenuItem(Locale.Light, SetTheme)
{
Checked = settings.CustomTheme == WindowsTheme.Light,
Tag = WindowsTheme.Light
},
new MenuItem(Locale.Dark, SetTheme)
{
Checked = settings.CustomTheme == WindowsTheme.Dark,
Tag = WindowsTheme.Dark
}
});
//&& hardware == null
if (temperatureUsage == null && settings.Performance == PerformanceType.Temperature)
{
settings.Performance = PerformanceType.CPU;
}
performanceMenu = new MenuItem(Locale.Performance, new MenuItem[]
{
new MenuItem(Locale.CPU, SetPerformance)
{
Checked = settings.Performance == PerformanceType.CPU,
Tag = PerformanceType.CPU
},
new MenuItem(Locale.Memory, SetPerformance)
{
Checked = settings.Performance == PerformanceType.Memory,
Tag = PerformanceType.Memory
}
});
if (networkTotal != null)
{
performanceMenu.MenuItems.Add(new MenuItem(Locale.Network, SetPerformance)
{
Checked = settings.Performance == PerformanceType.NetWork,
Tag = PerformanceType.NetWork
});
}
//|| hardware != null
if (temperatureUsage != null)
{
performanceMenu.MenuItems.Add(new MenuItem(Locale.Temperature, SetPerformance)
{
Checked = settings.Performance == PerformanceType.Temperature,
Tag = PerformanceType.Temperature
});
}
startupMenu = new MenuItem(Locale.Startup, OnSetStartup)
{
Checked = IsStartupEnabled()
};
MenuItem[] childen = new MenuItem[] { runnerMenu, themeMenu, performanceMenu, startupMenu, new MenuItem(Locale.Exit, Exit) };
notifyIcon = new NotifyIcon()
{
Icon = Properties.Resources.appIcon,
ContextMenu = new ContextMenu(childen),
Text = "",
Visible = true,
};
SetIcons();
SetAnimation();
CPUTick();
StartObserveCPU();
current = 1;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern bool SetMenuInfo(IntPtr hMenu, MENUINFO lpcmi);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern bool SetMenuItemInfo(IntPtr hMenu, int uItem, bool fByPosition, MENUITEMINFO lpmii);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class MENUINFO
{
public int cbSize = Marshal.SizeOf(typeof(MENUINFO));
public int fMask = 0x10; //MIM_STYLE
public int dwStyle = 0x4000000; //MNS_CHECKORBMP
public uint cyMax;
public IntPtr hbrBack;
public int dwContextHelpID;
public IntPtr dwMenuData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class MENUITEMINFO
{
public int cbSize = Marshal.SizeOf(typeof(MENUITEMINFO));
public int fMask = 0x80; //MIIM_BITMAP
public int fType;
public int fState;
public int wID;
public IntPtr hSubMenu;
public IntPtr hbmpChecked;
public IntPtr hbmpUnchecked;
public IntPtr dwItemData;
public IntPtr dwTypeData;
public int cch;
public IntPtr hbmpItem;
}
private void RunnerMenu_Popup(object sender, EventArgs e)
{
var info = new MENUITEMINFO();
int i = 0;
foreach (MenuItem item in ((Menu)sender).MenuItems)
{
Icon icon = null;
try
{
icon = (Icon)Properties.Resources.ResourceManager.GetObject($"{item.Tag as string}_0");
}
catch (Exception)
{ }
if (item.Visible && icon != null)
{
try
{
info.hbmpItem = icon.ToBitmap().GetHbitmap();
SetMenuItemInfo(((Menu)sender).Handle, i, true, info);
}
catch (Exception)
{
}
i++;
}
}
}
private void MainWindow_SourceInitialized(object sender, EventArgs e)
{
var listener = new ThemeListener(this);
listener.ThemeChanged += ThemeChanged;
Visibility = Visibility.Hidden;
Hide();
Init();
}
private void ThemeChanged(WindowsTheme theme)
{
systemTheme = theme;
SetIcons();
}
private void SetAnimation()
{
animateTimer.Interval = ANIMATE_TIMER_DEFAULT_INTERVAL;
animateTimer.Tick += new EventHandler(AnimationTick);
}
private void AnimationTick(object sender, EventArgs e)
{
if (icons.Length <= current) current = 0;
notifyIcon.Icon = icons[current];
current = (current + 1) % icons.Length;
}
private float netMaxMB = 1;
private void CPUTick()
{
float c = cpuUsage.NextValue();
float m = memoryAvailable.NextValue();
m = 100 - (m * 100 / MemoryTotleMbytes);
float s = settings.Performance == PerformanceType.Memory ? m : c;
string text = $"{Locale.CPU}: {c:f1}%\n{Locale.Memory}: {m:f1}%";
if(networkTotal != null)
{
float n = networkTotal.NextValue() / 1048576;
netMaxMB = Math.Max(netMaxMB, n);
if (settings.Performance == PerformanceType.NetWork) s = n * 100 / netMaxMB;
if(n < 1)
{
text += $"\n{Locale.Network}: {(n * 1024):f1}KB/s";
}
else
{
text += $"\n{Locale.Network}: {n:f1}MB/s";
}
}
if (temperatureUsage != null)
{
float t = temperatureUsage.NextValue() - (float)273.15;
if (settings.Performance == PerformanceType.Temperature) s = t;
text += $"\n{Locale.Temperature}: {t:f1}℃";
}
//else if(hardware != null)
//{
// float t = hardware.GetTemperature();
// if (settings.Performance == PerformanceType.Temperature) s = t;
// text += $"\nTemperature: {t:f1}℃";
//}
notifyIcon.Text = text;
s = ANIMATE_TIMER_DEFAULT_INTERVAL / (float)Math.Max(1.0f, Math.Min(20.0f, s / 5.0f));
animateTimer.Stop();
animateTimer.Interval = (int)s;
animateTimer.Start();
}
private void ObserveCPUTick(object sender, EventArgs e)
{
CPUTick();
}
private void StartObserveCPU()
{
cpuTimer.Interval = CPU_TIMER_DEFAULT_INTERVAL;
cpuTimer.Tick += new EventHandler(ObserveCPUTick);
cpuTimer.Start();
}
private void Exit(object sender, EventArgs e)
{
Close();
}
private void SetPerformance(object sender, EventArgs e)
{
MenuItem item = (MenuItem)sender;
UpdateCheckedState(item, performanceMenu);
settings.Performance = (PerformanceType)item.Tag;
settings.Save();
}
private void SetRunner(object sender, EventArgs e)
{
MenuItem item = (MenuItem)sender;
UpdateCheckedState(item, runnerMenu);
settings.Runner = (string)item.Tag;
SetIcons();
settings.Save();
}
private void SetTheme(object sender, EventArgs e)
{
MenuItem item = (MenuItem)sender;
UpdateCheckedState(item, themeMenu);
settings.CustomTheme = (WindowsTheme)item.Tag;
SetIcons();
settings.Save();
}
private void UpdateCheckedState(MenuItem sender, MenuItem menu)
{
foreach (MenuItem item in menu.MenuItems)
{
item.Checked = false;
}
sender.Checked = true;
}
private bool IsStartupEnabled()
{
string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";
using (RegistryKey rKey = Registry.CurrentUser.OpenSubKey(keyName))
{
return rKey.GetValue(Settings.AppName) != null;
}
}
private void SetIcons()
{
System.Resources.ResourceManager resourceManager = Properties.Resources.ResourceManager;
List<Icon> list = new List<Icon>();
var theme = systemTheme;
if (settings.CustomTheme != WindowsTheme.Default) theme = settings.CustomTheme;
int i = 0;
Icon icon = null;
do
{
try
{
icon = (Icon)resourceManager.GetObject(
$"{(theme == WindowsTheme.Dark ? "dark_" : "")}" +
$"{settings.Runner}_" +
$"{i++}");
if (icon != null) list.Add(icon);
}
catch (Exception)
{ }
} while (icon != null);
if (RunnerIcon.SymmetryIcon(settings.Runner))
for (i = list.Count - 2; i > 0; i--)
{
list.Add(list[i]);
}
if (list.Count == 0)
{
list.Add(Properties.Resources.appIcon);
}
icons = list.ToArray();
}
private void OnSetStartup(object sender, EventArgs e)
{
startupMenu.Checked = !startupMenu.Checked;
SetStartup(startupMenu.Checked);
settings.Save();
}
private void SetStartup(bool start)
{
string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";
using (RegistryKey rKey = Registry.CurrentUser.OpenSubKey(keyName, true))
{
if (start)
{
rKey.SetValue(Settings.AppName, Process.GetCurrentProcess().MainModule.FileName);
}
else
{
rKey.DeleteValue(Settings.AppName, false);
}
rKey.Close();
}
}
}
}