Files
Analog_System_Monitor/analog_system_monitor_dotnet/TrayApp.cs
2026-01-16 09:22:10 +01:00

87 lines
2.2 KiB
C#

using System;
using System.Drawing;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
namespace analog_system_monitor
{
public class TrayApp : ApplicationContext
{
private NotifyIcon trayIcon;
private Thread workerThread;
private bool running = true;
public TrayApp()
{
trayIcon = new NotifyIcon()
{
Icon = LoadEmbeddedIcon(),
Text = "Analog System Monitor",
Visible = true,
ContextMenuStrip = BuildMenu()
};
workerThread = new Thread(WorkerLoop)
{
IsBackground = true
};
workerThread.Start();
}
private Icon LoadEmbeddedIcon()
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "analog_system_monitor.telemetry_icon.ico";
using var stream = assembly.GetManifestResourceStream(resourceName);
if (stream == null)
{
MessageBox.Show("Embedded icon not found: " + resourceName);
return SystemIcons.Application;
}
return new Icon(stream);
}
private ContextMenuStrip BuildMenu()
{
var menu = new ContextMenuStrip();
var exitItem = new ToolStripMenuItem("Exit");
exitItem.Click += (s, e) => ExitApp();
menu.Items.Add(exitItem);
return menu;
}
private void WorkerLoop()
{
var telemetry = new Telemetry();
telemetry.Initialize();
while (running)
{
telemetry.UpdateAndSend();
Thread.Sleep(telemetry.UpdateRateMs);
}
}
private void ExitApp()
{
running = false;
try
{
workerThread?.Join(500);
}
catch { }
trayIcon.Visible = false;
trayIcon.Dispose();
Application.Exit();
}
}
}