-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPingStatusBarApplicationContext.cs
98 lines (83 loc) · 2.89 KB
/
PingStatusBarApplicationContext.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
using System;
using System.Drawing;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace PingStatusBarIndicator
{
class PingStatusBarApplicationContext : ApplicationContext
{
private readonly NotifyIcon _trayIcon;
private readonly System.Windows.Forms.Timer _pingTimer;
private readonly Ping _ping;
private readonly int _historyLength = 10;
private readonly bool[] _pingResults;
private int _pingIndex;
public PingStatusBarApplicationContext()
{
_pingResults = new bool[_historyLength];
_ping = new Ping();
_ping.PingCompleted += OnPingCompleted;
_pingTimer = new System.Windows.Forms.Timer
{
Interval = 1000,
};
_pingTimer.Tick += OnPingTimerTick;
_pingTimer.Start();
_trayIcon = new NotifyIcon
{
Icon = CreateIcon(Color.White),
Visible = true,
// ContextMenu = new ContextMenu(new[] { new MenuItem("Exit", Exit) }),
};
_trayIcon.ContextMenuStrip = new ContextMenuStrip();
_trayIcon.ContextMenuStrip.Items.Add(new ToolStripMenuItem("Exit", null, Exit));
}
private void OnPingTimerTick(object sender, EventArgs e)
{
_ping.SendAsync("8.8.8.8", 1000);
}
private void OnPingCompleted(object sender, PingCompletedEventArgs e)
{
bool success = e.Reply?.Status == IPStatus.Success;
_pingResults[_pingIndex] = success;
_pingIndex = (_pingIndex + 1) % _historyLength;
int successfulPings = 0;
for (int i = 0; i < _historyLength; i++)
{
if (_pingResults[i]) successfulPings++;
}
double successRate = (double)successfulPings / _historyLength;
_trayIcon.Icon = CreateIcon(GetColorBySuccessRate(successRate));
}
private Color GetColorBySuccessRate(double successRate)
{
if (successRate >= 0.9) return Color.Green;
if (successRate >= 0.5) return Color.Yellow;
return Color.Red;
}
private Icon CreateIcon(Color color)
{
var bitmap = new Bitmap(16, 16);
using (var g = Graphics.FromImage(bitmap))
{
g.Clear(color);
}
return Icon.FromHandle(bitmap.GetHicon());
}
private void Exit(object sender, EventArgs e)
{
_trayIcon.Visible = false;
Application.Exit();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_trayIcon.Dispose();
_pingTimer.Dispose();
_ping.Dispose();
}
base.Dispose(disposing);
}
}
}