From 58cef111a12e541bb3d1c1723a05fc4c543fb045 Mon Sep 17 00:00:00 2001
From: PhyxionNL <7643972+PhyxionNL@users.noreply.github.com>
Date: Sun, 9 Oct 2022 13:22:57 +0200
Subject: [PATCH] Use file-scoped namespaces (#842)
---
.editorconfig | 1 -
LibreHardwareMonitor/Program.cs | 91 +-
LibreHardwareMonitor/UI/AboutBox.cs | 45 +-
LibreHardwareMonitor/UI/AuthForm.cs | 69 +-
LibreHardwareMonitor/UI/Gadget.cs | 329 +-
LibreHardwareMonitor/UI/GadgetWindow.cs | 1059 ++-
LibreHardwareMonitor/UI/HardwareNode.cs | 241 +-
LibreHardwareMonitor/UI/HardwareTypeImage.cs | 117 +-
LibreHardwareMonitor/UI/IExpandPersistNode.cs | 11 +-
LibreHardwareMonitor/UI/MainForm.cs | 2043 +++---
LibreHardwareMonitor/UI/Node.cs | 295 +-
.../UI/NodeToolTipProvider.cs | 11 +-
LibreHardwareMonitor/UI/NotifyIconAdv.cs | 1463 ++--
LibreHardwareMonitor/UI/ParameterForm.cs | 225 +-
LibreHardwareMonitor/UI/PlotPanel.cs | 711 +-
LibreHardwareMonitor/UI/PortForm.cs | 135 +-
LibreHardwareMonitor/UI/ScaledPlotModel.cs | 45 +-
LibreHardwareMonitor/UI/SensorGadget.cs | 1386 ++--
LibreHardwareMonitor/UI/SensorNode.cs | 433 +-
LibreHardwareMonitor/UI/SensorNotifyIcon.cs | 497 +-
LibreHardwareMonitor/UI/ShowDesktop.cs | 277 +-
LibreHardwareMonitor/UI/SplitContainerAdv.cs | 221 +-
LibreHardwareMonitor/UI/StartupManager.cs | 267 +-
LibreHardwareMonitor/UI/SystemTray.cs | 307 +-
.../UI/ToolStripRadioButtonMenuItem.cs | 445 +-
LibreHardwareMonitor/UI/TreeModel.cs | 189 +-
LibreHardwareMonitor/UI/TypeNode.cs | 241 +-
LibreHardwareMonitor/UI/UnitManager.cs | 54 +-
LibreHardwareMonitor/UI/UpdateVisitor.cs | 35 +-
LibreHardwareMonitor/UI/UserOption.cs | 89 +-
LibreHardwareMonitor/UI/UserRadioGroup.cs | 93 +-
.../Utilities/EmbeddedResources.cs | 75 +-
LibreHardwareMonitor/Utilities/HttpServer.cs | 1065 ++-
LibreHardwareMonitor/Utilities/IconFactory.cs | 355 +-
LibreHardwareMonitor/Utilities/Logger.cs | 317 +-
.../Utilities/PersistentSettings.cs | 369 +-
LibreHardwareMonitor/WMI/Hardware.cs | 47 +-
LibreHardwareMonitor/WMI/IWmiObject.cs | 21 +-
LibreHardwareMonitor/WMI/Sensor.cs | 77 +-
.../Hardware/Battery/Battery.cs | 399 +-
.../Hardware/Battery/BatteryGroup.cs | 321 +-
.../Hardware/CompositeSensor.cs | 57 +-
LibreHardwareMonitorLib/Hardware/Computer.cs | 1299 ++--
LibreHardwareMonitorLib/Hardware/Control.cs | 153 +-
.../Controller/AeroCool/AeroCoolGroup.cs | 73 +-
.../Hardware/Controller/AeroCool/P7-H1.cs | 153 +-
.../AquaComputer/AquaComputerGroup.cs | 155 +-
.../Controller/AquaComputer/AquastreamXT.cs | 270 +-
.../Controller/AquaComputer/D5Next.cs | 99 +-
.../Hardware/Controller/AquaComputer/MPS.cs | 173 +-
.../Hardware/Controller/AquaComputer/Octo.cs | 339 +-
.../Controller/Heatmaster/Heatmaster.cs | 507 +-
.../Controller/Heatmaster/HeatmasterGroup.cs | 289 +-
.../Hardware/Controller/Nzxt/GridV3.cs | 305 +-
.../Hardware/Controller/Nzxt/KrakenX3.cs | 269 +-
.../Hardware/Controller/Nzxt/NzxtGroup.cs | 115 +-
.../Controller/TBalancer/TBalancer.cs | 583 +-
.../Controller/TBalancer/TBalancerGroup.cs | 259 +-
.../Hardware/Cpu/Amd0FCpu.cs | 259 +-
.../Hardware/Cpu/Amd10Cpu.cs | 839 ++-
.../Hardware/Cpu/Amd17Cpu.cs | 1027 ++-
.../Hardware/Cpu/AmdCpu.cs | 49 +-
.../Hardware/Cpu/CpuGroup.cs | 383 +-
LibreHardwareMonitorLib/Hardware/Cpu/CpuId.cs | 479 +-
.../Hardware/Cpu/CpuLoad.cs | 183 +-
.../Hardware/Cpu/GenericCpu.cs | 513 +-
.../Hardware/Cpu/IntelCpu.cs | 1299 ++--
.../Hardware/D3DDisplayDevice.cs | 461 +-
.../Hardware/FirmwareTable.cs | 145 +-
.../Hardware/Gpu/AmdGpu.cs | 1387 ++--
.../Hardware/Gpu/AmdGpuGroup.cs | 179 +-
.../Hardware/Gpu/GenericGpu.cs | 35 +-
.../Hardware/Gpu/IntelGpuGroup.cs | 123 +-
.../Hardware/Gpu/IntelIntegratedGpu.cs | 203 +-
.../Hardware/Gpu/NvidiaGpu.cs | 2131 +++---
.../Hardware/Gpu/NvidiaGroup.cs | 133 +-
.../Hardware/GroupAffinity.cs | 163 +-
LibreHardwareMonitorLib/Hardware/Hardware.cs | 203 +-
.../Hardware/HardwareType.cs | 41 +-
LibreHardwareMonitorLib/Hardware/IComputer.cs | 183 +-
LibreHardwareMonitorLib/Hardware/IControl.cs | 51 +-
LibreHardwareMonitorLib/Hardware/IElement.cs | 31 +-
LibreHardwareMonitorLib/Hardware/IGroup.cs | 37 +-
LibreHardwareMonitorLib/Hardware/IHardware.cs | 117 +-
.../Hardware/IHardwareChanged.cs | 13 +-
.../Hardware/IParameter.cs | 67 +-
LibreHardwareMonitorLib/Hardware/ISensor.cs | 231 +-
.../Hardware/ISensorLimits.cs | 53 +-
LibreHardwareMonitorLib/Hardware/ISettings.cs | 55 +-
LibreHardwareMonitorLib/Hardware/IVisitor.cs | 51 +-
.../Hardware/Identifier.cs | 211 +-
LibreHardwareMonitorLib/Hardware/InpOut.cs | 327 +-
.../Hardware/KernelDriver.cs | 309 +-
.../Hardware/Memory/GenericLinuxMemory.cs | 129 +-
.../Hardware/Memory/GenericWindowsMemory.cs | 91 +-
.../Hardware/Memory/MemoryGroup.cs | 35 +-
.../Hardware/Motherboard/Identification.cs | 723 +-
.../Hardware/Motherboard/Lpc/Chip.cs | 257 +-
.../Motherboard/Lpc/EC/EmbeddedController.cs | 851 ++-
.../Lpc/EC/EmbeddedControllerReader.cs | 7 +-
.../Lpc/EC/EmbeddedControllerSource.cs | 45 +-
.../Lpc/EC/IEmbeddedControllerIO.cs | 11 +-
.../Lpc/EC/WindowsEmbeddedController.cs | 21 +-
.../Lpc/EC/WindowsEmbeddedControllerIO.cs | 447 +-
.../Hardware/Motherboard/Lpc/F718XX.cs | 301 +-
.../Hardware/Motherboard/Lpc/ISuperIO.cs | 35 +-
.../Hardware/Motherboard/Lpc/IT87XX.cs | 933 ++-
.../Hardware/Motherboard/Lpc/LMSensors.cs | 511 +-
.../Hardware/Motherboard/Lpc/LPcPort.cs | 181 +-
.../Hardware/Motherboard/Lpc/LpcIO.cs | 1197 ++-
.../Hardware/Motherboard/Lpc/Nct677X.cs | 1807 +++--
.../Hardware/Motherboard/Lpc/W836XX.cs | 905 ++-
.../Hardware/Motherboard/Manufacturer.cs | 95 +-
.../Hardware/Motherboard/Model.cs | 287 +-
.../Hardware/Motherboard/Motherboard.cs | 299 +-
.../Hardware/Motherboard/MotherboardGroup.cs | 45 +-
.../Hardware/Motherboard/SuperIOHardware.cs | 6459 ++++++++---------
.../Hardware/Network/Network.cs | 177 +-
.../Hardware/Network/NetworkGroup.cs | 235 +-
LibreHardwareMonitorLib/Hardware/OpCode.cs | 527 +-
LibreHardwareMonitorLib/Hardware/Parameter.cs | 149 +-
.../Hardware/ParameterDescription.cs | 61 +-
.../Hardware/Psu/Corsair/CorsairPsu.cs | 887 ++-
.../Hardware/Psu/Corsair/CorsairPsuGroup.cs | 103 +-
LibreHardwareMonitorLib/Hardware/Ring0.cs | 977 ++-
LibreHardwareMonitorLib/Hardware/RyzenSMU.cs | 1365 ++--
LibreHardwareMonitorLib/Hardware/SMBios.cs | 2839 ++++----
LibreHardwareMonitorLib/Hardware/Sensor.cs | 491 +-
.../Hardware/SensorVisitor.cs | 113 +-
.../Hardware/Storage/ATAStorage.cs | 485 +-
.../Hardware/Storage/AbstractStorage.cs | 519 +-
.../Hardware/Storage/GenericHardDisk.cs | 157 +-
.../Hardware/Storage/INVMeDrive.cs | 15 +-
.../Hardware/Storage/ISmart.cs | 21 +-
.../Hardware/Storage/NVMeGeneric.cs | 309 +-
.../Hardware/Storage/NVMeHealthInfo.cs | 45 +-
.../Hardware/Storage/NVMeInfo.cs | 31 +-
.../Hardware/Storage/NVMeIntel.cs | 275 +-
.../Hardware/Storage/NVMeIntelRst.cs | 275 +-
.../Hardware/Storage/NVMeSamsung.cs | 397 +-
.../Hardware/Storage/NVMeSmart.cs | 311 +-
.../Hardware/Storage/NVMeWindows.cs | 231 +-
.../Hardware/Storage/NamePrefixAttribute.cs | 21 +-
.../Hardware/Storage/RequireSmartAttribute.cs | 21 +-
.../Hardware/Storage/SmartAttribute.cs | 181 +-
.../Hardware/Storage/SmartNames.cs | 265 +-
.../Hardware/Storage/SsdIndilinx.cs | 67 +-
.../Hardware/Storage/SsdIntel.cs | 79 +-
.../Hardware/Storage/SsdMicron.cs | 185 +-
.../Hardware/Storage/SsdPlextor.cs | 33 +-
.../Hardware/Storage/SsdSamsung.cs | 89 +-
.../Hardware/Storage/SsdSandforce.cs | 111 +-
.../Hardware/Storage/StorageGeneric.cs | 37 +-
.../Hardware/Storage/StorageGroup.cs | 67 +-
.../Hardware/Storage/StorageInfo.cs | 33 +-
.../Hardware/Storage/WindowsSmart.cs | 295 +-
.../Hardware/Storage/WindowsStorage.cs | 135 +-
.../Hardware/ThreadAffinity.cs | 195 +-
LibreHardwareMonitorLib/Interop/AdvApi32.cs | 275 +-
LibreHardwareMonitorLib/Interop/AtiAdlxx.cs | 1041 ++-
LibreHardwareMonitorLib/Interop/CfgMgr32.cs | 29 +-
LibreHardwareMonitorLib/Interop/D3dkmdt.cs | 69 +-
LibreHardwareMonitorLib/Interop/D3dkmth.cs | 969 ++-
LibreHardwareMonitorLib/Interop/Ftd2xx.cs | 339 +-
LibreHardwareMonitorLib/Interop/Gdi32.cs | 35 +-
LibreHardwareMonitorLib/Interop/InpOut.cs | 23 +-
LibreHardwareMonitorLib/Interop/Kernel32.cs | 3071 ++++----
LibreHardwareMonitorLib/Interop/LibC.cs | 19 +-
LibreHardwareMonitorLib/Interop/NtDll.cs | 137 +-
LibreHardwareMonitorLib/Interop/NvApi.cs | 1195 ++-
LibreHardwareMonitorLib/Interop/NvidiaML.cs | 769 +-
LibreHardwareMonitorLib/Interop/Ring0.cs | 35 +-
LibreHardwareMonitorLib/Interop/SetupApi.cs | 93 +-
LibreHardwareMonitorLib/Interop/WinNt.cs | 61 +-
.../Software/OperatingSystem.cs | 49 +-
175 files changed, 34026 insertions(+), 34204 deletions(-)
diff --git a/.editorconfig b/.editorconfig
index 9422b2d..e326842 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -38,7 +38,6 @@ csharp_indent_labels = one_less_than_current
# Modifier preferences
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion
-
# avoid this. unless absolutely necessary
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
diff --git a/LibreHardwareMonitor/Program.cs b/LibreHardwareMonitor/Program.cs
index 25ce6f2..d4a3bda 100644
--- a/LibreHardwareMonitor/Program.cs
+++ b/LibreHardwareMonitor/Program.cs
@@ -9,56 +9,55 @@ using System.IO;
using System.Windows.Forms;
using LibreHardwareMonitor.UI;
-namespace LibreHardwareMonitor
+namespace LibreHardwareMonitor;
+
+public static class Program
{
- public static class Program
+ [STAThread]
+ public static void Main()
{
- [STAThread]
- public static void Main()
- {
- if (!AllRequiredFilesAvailable())
- Environment.Exit(0);
+ if (!AllRequiredFilesAvailable())
+ Environment.Exit(0);
- Application.EnableVisualStyles();
- Application.SetCompatibleTextRenderingDefault(false);
- using (MainForm form = new MainForm())
+ Application.EnableVisualStyles();
+ Application.SetCompatibleTextRenderingDefault(false);
+ using (MainForm form = new MainForm())
+ {
+ form.FormClosed += delegate
{
- form.FormClosed += delegate
- {
- Application.Exit();
- };
- Application.Run();
- }
- }
-
- private static bool IsFileAvailable(string fileName)
- {
- string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar;
- if (!File.Exists(path + fileName))
- {
- MessageBox.Show("The following file could not be found: " + fileName +
- "\nPlease extract all files from the archive.", "Error",
- MessageBoxButtons.OK, MessageBoxIcon.Error);
- return false;
- }
- return true;
- }
-
- private static bool AllRequiredFilesAvailable()
- {
- if (!IsFileAvailable("Aga.Controls.dll"))
- return false;
-
- if (!IsFileAvailable("LibreHardwareMonitorLib.dll"))
- return false;
-
- if (!IsFileAvailable("OxyPlot.dll"))
- return false;
-
- if (!IsFileAvailable("OxyPlot.WindowsForms.dll"))
- return false;
-
- return true;
+ Application.Exit();
+ };
+ Application.Run();
}
}
+
+ private static bool IsFileAvailable(string fileName)
+ {
+ string path = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar;
+ if (!File.Exists(path + fileName))
+ {
+ MessageBox.Show("The following file could not be found: " + fileName +
+ "\nPlease extract all files from the archive.", "Error",
+ MessageBoxButtons.OK, MessageBoxIcon.Error);
+ return false;
+ }
+ return true;
+ }
+
+ private static bool AllRequiredFilesAvailable()
+ {
+ if (!IsFileAvailable("Aga.Controls.dll"))
+ return false;
+
+ if (!IsFileAvailable("LibreHardwareMonitorLib.dll"))
+ return false;
+
+ if (!IsFileAvailable("OxyPlot.dll"))
+ return false;
+
+ if (!IsFileAvailable("OxyPlot.WindowsForms.dll"))
+ return false;
+
+ return true;
+ }
}
diff --git a/LibreHardwareMonitor/UI/AboutBox.cs b/LibreHardwareMonitor/UI/AboutBox.cs
index d664227..41cf6f0 100644
--- a/LibreHardwareMonitor/UI/AboutBox.cs
+++ b/LibreHardwareMonitor/UI/AboutBox.cs
@@ -8,28 +8,27 @@ using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
-namespace LibreHardwareMonitor.UI
-{
- public sealed partial class AboutBox : Form
- {
- public AboutBox()
- {
- InitializeComponent();
- Font = SystemFonts.MessageBoxFont;
- label3.Text = "Version " + Application.ProductVersion;
- projectLinkLabel.Links.Remove(projectLinkLabel.Links[0]);
- projectLinkLabel.Links.Add(0, projectLinkLabel.Text.Length, "https://github.com/LibreHardwareMonitor/LibreHardwareMonitor");
- licenseLinkLabel.Links.Remove(licenseLinkLabel.Links[0]);
- licenseLinkLabel.Links.Add(0, licenseLinkLabel.Text.Length, "https://www.mozilla.org/en-US/MPL/2.0/");
- }
+namespace LibreHardwareMonitor.UI;
- private void LinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
- {
- try
- {
- Process.Start(new ProcessStartInfo(e.Link.LinkData.ToString()));
- }
- catch { }
- }
+public sealed partial class AboutBox : Form
+{
+ public AboutBox()
+ {
+ InitializeComponent();
+ Font = SystemFonts.MessageBoxFont;
+ label3.Text = "Version " + Application.ProductVersion;
+ projectLinkLabel.Links.Remove(projectLinkLabel.Links[0]);
+ projectLinkLabel.Links.Add(0, projectLinkLabel.Text.Length, "https://github.com/LibreHardwareMonitor/LibreHardwareMonitor");
+ licenseLinkLabel.Links.Remove(licenseLinkLabel.Links[0]);
+ licenseLinkLabel.Links.Add(0, licenseLinkLabel.Text.Length, "https://www.mozilla.org/en-US/MPL/2.0/");
}
-}
+
+ private void LinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
+ {
+ try
+ {
+ Process.Start(new ProcessStartInfo(e.Link.LinkData.ToString()));
+ }
+ catch { }
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/AuthForm.cs b/LibreHardwareMonitor/UI/AuthForm.cs
index ffc9b12..b590495 100644
--- a/LibreHardwareMonitor/UI/AuthForm.cs
+++ b/LibreHardwareMonitor/UI/AuthForm.cs
@@ -7,41 +7,40 @@
using System;
using System.Windows.Forms;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public partial class AuthForm : Form
{
- public partial class AuthForm : Form
+ private readonly MainForm _parent;
+
+ public AuthForm(MainForm m)
{
- private readonly MainForm _parent;
-
- public AuthForm(MainForm m)
- {
- InitializeComponent();
- _parent = m;
- }
-
- private void AuthForm_Load(object sender, EventArgs e)
- {
- httpAuthUsernameTextBox.Enabled = httpAuthPasswordTextBox.Enabled = enableHTTPAuthCheckBox.Checked = _parent.Server.AuthEnabled;
- httpAuthUsernameTextBox.Text = _parent.Server.UserName;
- }
-
- private void HttpAuthCancelButton_Click(object sender, EventArgs e)
- {
- Close();
- }
-
- private void HttpAuthOkButton_Click(object sender, EventArgs e)
- {
- _parent.Server.UserName = httpAuthUsernameTextBox.Text;
- _parent.Server.Password = httpAuthPasswordTextBox.Text;
- _parent.Server.AuthEnabled = enableHTTPAuthCheckBox.Checked;
- _parent.AuthWebServerMenuItemChecked = _parent.Server.AuthEnabled;
- Close();
- }
-
- private void EnableHTTPAuthCheckBox_CheckedChanged(object sender, EventArgs e)
- {
- httpAuthUsernameTextBox.Enabled = httpAuthPasswordTextBox.Enabled = enableHTTPAuthCheckBox.Checked;
- }
+ InitializeComponent();
+ _parent = m;
}
-}
+
+ private void AuthForm_Load(object sender, EventArgs e)
+ {
+ httpAuthUsernameTextBox.Enabled = httpAuthPasswordTextBox.Enabled = enableHTTPAuthCheckBox.Checked = _parent.Server.AuthEnabled;
+ httpAuthUsernameTextBox.Text = _parent.Server.UserName;
+ }
+
+ private void HttpAuthCancelButton_Click(object sender, EventArgs e)
+ {
+ Close();
+ }
+
+ private void HttpAuthOkButton_Click(object sender, EventArgs e)
+ {
+ _parent.Server.UserName = httpAuthUsernameTextBox.Text;
+ _parent.Server.Password = httpAuthPasswordTextBox.Text;
+ _parent.Server.AuthEnabled = enableHTTPAuthCheckBox.Checked;
+ _parent.AuthWebServerMenuItemChecked = _parent.Server.AuthEnabled;
+ Close();
+ }
+
+ private void EnableHTTPAuthCheckBox_CheckedChanged(object sender, EventArgs e)
+ {
+ httpAuthUsernameTextBox.Enabled = httpAuthPasswordTextBox.Enabled = enableHTTPAuthCheckBox.Checked;
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/Gadget.cs b/LibreHardwareMonitor/UI/Gadget.cs
index a69c5cc..f701690 100644
--- a/LibreHardwareMonitor/UI/Gadget.cs
+++ b/LibreHardwareMonitor/UI/Gadget.cs
@@ -8,172 +8,171 @@ using System;
using System.Drawing;
using System.Windows.Forms;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public abstract class Gadget : IDisposable
{
- public abstract class Gadget : IDisposable
+ private readonly GadgetWindow _window;
+
+ public event EventHandler VisibleChanged;
+
+ protected Gadget()
{
- private readonly GadgetWindow _window;
-
- public event EventHandler VisibleChanged;
-
- protected Gadget()
+ _window = new GadgetWindow();
+ _window.Paint += delegate (object sender, PaintEventArgs e)
{
- _window = new GadgetWindow();
- _window.Paint += delegate (object sender, PaintEventArgs e)
- {
- OnPaint(e);
- };
- }
-
- public virtual void Dispose()
- {
- _window.Dispose();
- }
-
- public Point Location
- {
- get
- {
- return _window.Location;
- }
- set
- {
- _window.Location = value;
- }
- }
-
- public event EventHandler LocationChanged
- {
- add
- {
- _window.LocationChanged += value;
- }
- remove
- {
- _window.LocationChanged -= value;
- }
- }
-
- public virtual Size Size
- {
- get
- {
- return _window.Size;
- }
- set
- {
- _window.Size = value;
- }
- }
-
- public event EventHandler SizeChanged
- {
- add
- {
- _window.SizeChanged += value;
- }
- remove
- {
- _window.SizeChanged -= value;
- }
- }
-
- public byte Opacity
- {
- get
- {
- return _window.Opacity;
- }
- set
- {
- _window.Opacity = value;
- }
- }
-
- public bool LockPositionAndSize
- {
- get
- {
- return _window.LockPositionAndSize;
- }
- set
- {
- _window.LockPositionAndSize = value;
- }
- }
-
- public bool AlwaysOnTop
- {
- get
- {
- return _window.AlwaysOnTop;
- }
- set
- {
- _window.AlwaysOnTop = value;
- }
- }
-
- public ContextMenuStrip ContextMenuStrip
- {
- get
- {
- return _window.ContextMenuStrip;
- }
- set
- {
- _window.ContextMenuStrip = value;
- }
- }
-
- public event HitTestEventHandler HitTest
- {
- add
- {
- _window.HitTest += value;
- }
- remove
- {
- _window.HitTest -= value;
- }
- }
-
- public event MouseEventHandler MouseDoubleClick
- {
- add
- {
- _window.MouseDoubleClick += value;
- }
- remove
- {
- _window.MouseDoubleClick -= value;
- }
- }
-
- public bool Visible
- {
- get
- {
- return _window.Visible;
- }
- set
- {
- if (value != _window.Visible)
- {
- _window.Visible = value;
- VisibleChanged?.Invoke(this, EventArgs.Empty);
-
- if (value)
- Redraw();
- }
- }
- }
-
- public void Redraw()
- {
- _window.Redraw();
- }
-
- protected abstract void OnPaint(PaintEventArgs e);
+ OnPaint(e);
+ };
}
-}
+
+ public virtual void Dispose()
+ {
+ _window.Dispose();
+ }
+
+ public Point Location
+ {
+ get
+ {
+ return _window.Location;
+ }
+ set
+ {
+ _window.Location = value;
+ }
+ }
+
+ public event EventHandler LocationChanged
+ {
+ add
+ {
+ _window.LocationChanged += value;
+ }
+ remove
+ {
+ _window.LocationChanged -= value;
+ }
+ }
+
+ public virtual Size Size
+ {
+ get
+ {
+ return _window.Size;
+ }
+ set
+ {
+ _window.Size = value;
+ }
+ }
+
+ public event EventHandler SizeChanged
+ {
+ add
+ {
+ _window.SizeChanged += value;
+ }
+ remove
+ {
+ _window.SizeChanged -= value;
+ }
+ }
+
+ public byte Opacity
+ {
+ get
+ {
+ return _window.Opacity;
+ }
+ set
+ {
+ _window.Opacity = value;
+ }
+ }
+
+ public bool LockPositionAndSize
+ {
+ get
+ {
+ return _window.LockPositionAndSize;
+ }
+ set
+ {
+ _window.LockPositionAndSize = value;
+ }
+ }
+
+ public bool AlwaysOnTop
+ {
+ get
+ {
+ return _window.AlwaysOnTop;
+ }
+ set
+ {
+ _window.AlwaysOnTop = value;
+ }
+ }
+
+ public ContextMenuStrip ContextMenuStrip
+ {
+ get
+ {
+ return _window.ContextMenuStrip;
+ }
+ set
+ {
+ _window.ContextMenuStrip = value;
+ }
+ }
+
+ public event HitTestEventHandler HitTest
+ {
+ add
+ {
+ _window.HitTest += value;
+ }
+ remove
+ {
+ _window.HitTest -= value;
+ }
+ }
+
+ public event MouseEventHandler MouseDoubleClick
+ {
+ add
+ {
+ _window.MouseDoubleClick += value;
+ }
+ remove
+ {
+ _window.MouseDoubleClick -= value;
+ }
+ }
+
+ public bool Visible
+ {
+ get
+ {
+ return _window.Visible;
+ }
+ set
+ {
+ if (value != _window.Visible)
+ {
+ _window.Visible = value;
+ VisibleChanged?.Invoke(this, EventArgs.Empty);
+
+ if (value)
+ Redraw();
+ }
+ }
+ }
+
+ public void Redraw()
+ {
+ _window.Redraw();
+ }
+
+ protected abstract void OnPaint(PaintEventArgs e);
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/GadgetWindow.cs b/LibreHardwareMonitor/UI/GadgetWindow.cs
index 19e3c00..45a302b 100644
--- a/LibreHardwareMonitor/UI/GadgetWindow.cs
+++ b/LibreHardwareMonitor/UI/GadgetWindow.cs
@@ -12,564 +12,563 @@ using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public sealed class GadgetWindow : NativeWindow, IDisposable
{
- public sealed class GadgetWindow : NativeWindow, IDisposable
+ private bool _visible;
+ private bool _alwaysOnTop;
+ private byte _opacity = 255;
+ private Point _location = new Point(100, 100);
+ private Size _size = new Size(130, 84);
+ private readonly MethodInfo _commandDispatch;
+ private IntPtr _handleBitmapDC;
+ private Size _bufferSize;
+ private Graphics _graphics;
+
+ public event EventHandler SizeChanged;
+ public event EventHandler LocationChanged;
+ public event HitTestEventHandler HitTest;
+ public event MouseEventHandler MouseDoubleClick;
+
+ public GadgetWindow()
{
- private bool _visible;
- private bool _alwaysOnTop;
- private byte _opacity = 255;
- private Point _location = new Point(100, 100);
- private Size _size = new Size(130, 84);
- private readonly MethodInfo _commandDispatch;
- private IntPtr _handleBitmapDC;
- private Size _bufferSize;
- private Graphics _graphics;
+ Type commandType = typeof(Form).Assembly.GetType("System.Windows.Forms.Command");
+ _commandDispatch = commandType.GetMethod("DispatchID",
+ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public,
+ null, new[] { typeof(int) }, null);
- public event EventHandler SizeChanged;
- public event EventHandler LocationChanged;
- public event HitTestEventHandler HitTest;
- public event MouseEventHandler MouseDoubleClick;
+ CreateHandle(CreateParams);
- public GadgetWindow()
+ // move window to the bottom
+ MoveToBottom(Handle);
+
+ // prevent window from fading to a glass sheet when peek is invoked
+ try
{
- Type commandType = typeof(Form).Assembly.GetType("System.Windows.Forms.Command");
- _commandDispatch = commandType.GetMethod("DispatchID",
- BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public,
- null, new[] { typeof(int) }, null);
+ bool value = true;
+ NativeMethods.DwmSetWindowAttribute(Handle, WindowAttribute.DWMWA_EXCLUDED_FROM_PEEK, ref value, Marshal.SizeOf(true));
+ }
+ catch (DllNotFoundException) { }
+ catch (EntryPointNotFoundException) { }
- CreateHandle(CreateParams);
+ CreateBuffer();
+ }
- // move window to the bottom
+ private void ShowDesktopChanged(bool showDesktop)
+ {
+ if (showDesktop)
+ MoveToTopMost(Handle);
+ else
MoveToBottom(Handle);
+ }
- // prevent window from fading to a glass sheet when peek is invoked
- try
+ private void MoveToBottom(IntPtr handle)
+ {
+ NativeMethods.SetWindowPos(handle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
+ }
+
+ private void MoveToTopMost(IntPtr handle)
+ {
+ NativeMethods.SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
+ }
+
+ private CreateParams CreateParams
+ {
+ get
+ {
+ CreateParams cp = new CreateParams
{
- bool value = true;
- NativeMethods.DwmSetWindowAttribute(Handle, WindowAttribute.DWMWA_EXCLUDED_FROM_PEEK, ref value, Marshal.SizeOf(true));
- }
- catch (DllNotFoundException) { }
- catch (EntryPointNotFoundException) { }
+ Width = 4096,
+ Height = 4096,
+ X = _location.X,
+ Y = _location.Y,
+ ExStyle = WS_EX_LAYERED | WS_EX_TOOLWINDOW
+ };
+ return cp;
+ }
+ }
+
+ protected override void WndProc(ref Message message)
+ {
+ switch (message.Msg)
+ {
+ case WM_COMMAND:
+ {
+ // need to dispatch the message for the context menu
+ if (message.LParam == IntPtr.Zero)
+ _commandDispatch.Invoke(null, new object[] {message.WParam.ToInt32() & 0xFFFF });
+ }
+ break;
+ case WM_NCHITTEST:
+ {
+ message.Result = (IntPtr)HitResult.Caption;
+ if (HitTest != null)
+ {
+ Point p = new Point(
+ Macros.GET_X_LPARAM(message.LParam) - _location.X,
+ Macros.GET_Y_LPARAM(message.LParam) - _location.Y
+ );
+ HitTestEventArgs e = new HitTestEventArgs(p, HitResult.Caption);
+ HitTest(this, e);
+ message.Result = (IntPtr)e.HitResult;
+ }
+ }
+ break;
+ case WM_NCLBUTTONDBLCLK:
+ {
+ MouseDoubleClick?.Invoke(this, new MouseEventArgs(MouseButtons.Left, 2, Macros.GET_X_LPARAM(message.LParam) - _location.X, Macros.GET_Y_LPARAM(message.LParam) - _location.Y, 0));
+ message.Result = IntPtr.Zero;
+ }
+ break;
+ case WM_NCRBUTTONDOWN:
+ {
+ message.Result = IntPtr.Zero;
+ }
+ break;
+ case WM_NCRBUTTONUP:
+ {
+ ContextMenuStrip?.Show(new Point(Macros.GET_X_LPARAM(message.LParam), Macros.GET_Y_LPARAM(message.LParam)));
+ message.Result = IntPtr.Zero;
+ }
+ break;
+ case WM_WINDOWPOSCHANGING:
+ {
+ WINDOWPOS wp = (WINDOWPOS)Marshal.PtrToStructure(message.LParam, typeof(WINDOWPOS));
+ if (!LockPositionAndSize)
+ {
+ // prevent the window from leaving the screen
+ if ((wp.flags & SWP_NOMOVE) == 0)
+ {
+ Rectangle rect = Screen.GetWorkingArea(new Rectangle(wp.x, wp.y, wp.cx, wp.cy));
+ const int margin = 16;
+ wp.x = Math.Max(wp.x, rect.Left - wp.cx + margin);
+ wp.x = Math.Min(wp.x, rect.Right - margin);
+ wp.y = Math.Max(wp.y, rect.Top - wp.cy + margin);
+ wp.y = Math.Min(wp.y, rect.Bottom - margin);
+ }
+
+ // update location and fire event
+ if ((wp.flags & SWP_NOMOVE) == 0)
+ {
+ if (_location.X != wp.x || _location.Y != wp.y)
+ {
+ _location = new Point(wp.x, wp.y);
+ LocationChanged?.Invoke(this, EventArgs.Empty);
+ }
+ }
+
+ // update size and fire event
+ if ((wp.flags & SWP_NOSIZE) == 0)
+ {
+ if (_size.Width != wp.cx || _size.Height != wp.cy)
+ {
+ _size = new Size(wp.cx, wp.cy);
+ SizeChanged?.Invoke(this, EventArgs.Empty);
+ }
+ }
+
+ // update the size of the layered window
+ if ((wp.flags & SWP_NOSIZE) == 0)
+ NativeMethods.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, ref _size, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero, 0);
+
+ // update the position of the layered window
+ if ((wp.flags & SWP_NOMOVE) == 0)
+ NativeMethods.SetWindowPos(Handle, IntPtr.Zero, _location.X, _location.Y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSENDCHANGING);
+ }
+
+ // do not forward any move or size messages
+ wp.flags |= SWP_NOSIZE | SWP_NOMOVE;
+
+ // suppress any frame changed events
+ wp.flags &= ~SWP_FRAMECHANGED;
+
+ Marshal.StructureToPtr(wp, message.LParam, false);
+ message.Result = IntPtr.Zero;
+ }
+ break;
+ default:
+ {
+ base.WndProc(ref message);
+ }
+ break;
+ }
+ }
+
+ private BlendFunction CreateBlendFunction()
+ {
+ return new BlendFunction { BlendOp = AC_SRC_OVER, BlendFlags = 0, SourceConstantAlpha = _opacity, AlphaFormat = AC_SRC_ALPHA };
+ }
+
+ private void CreateBuffer()
+ {
+ IntPtr handleScreenDC = NativeMethods.GetDC(IntPtr.Zero);
+ _handleBitmapDC = NativeMethods.CreateCompatibleDC(handleScreenDC);
+ NativeMethods.ReleaseDC(IntPtr.Zero, handleScreenDC);
+ _bufferSize = _size;
+
+ BITMAPINFO info = new BITMAPINFO();
+ info.Size = Marshal.SizeOf(info);
+ info.Width = _size.Width;
+ info.Height = -_size.Height;
+ info.BitCount = 32;
+ info.Planes = 1;
+
+ IntPtr hBmp = NativeMethods.CreateDIBSection(_handleBitmapDC, ref info, 0, out IntPtr _, IntPtr.Zero, 0);
+ IntPtr hBmpOld = NativeMethods.SelectObject(_handleBitmapDC, hBmp);
+ NativeMethods.DeleteObject(hBmpOld);
+
+ _graphics = Graphics.FromHdc(_handleBitmapDC);
+
+ if (Environment.OSVersion.Version.Major > 5)
+ {
+ _graphics.TextRenderingHint = TextRenderingHint.SystemDefault;
+ _graphics.SmoothingMode = SmoothingMode.HighQuality;
+ }
+ }
+
+ private void DisposeBuffer()
+ {
+ _graphics.Dispose();
+ NativeMethods.DeleteDC(_handleBitmapDC);
+ }
+
+ public void Dispose()
+ {
+ DisposeBuffer();
+ }
+
+ public PaintEventHandler Paint;
+
+ public void Redraw()
+ {
+ if (!_visible || Paint == null)
+ return;
+
+ if (_size != _bufferSize)
+ {
+ DisposeBuffer();
CreateBuffer();
}
- private void ShowDesktopChanged(bool showDesktop)
- {
- if (showDesktop)
- MoveToTopMost(Handle);
- else
- MoveToBottom(Handle);
- }
+ Paint(this, new PaintEventArgs(_graphics, new Rectangle(Point.Empty, _size)));
+ Point pointSource = Point.Empty;
+ BlendFunction blend = CreateBlendFunction();
+ NativeMethods.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, ref _size, _handleBitmapDC, ref pointSource, 0, ref blend, ULW_ALPHA);
+ // make sure the window is at the right location
+ NativeMethods.SetWindowPos(Handle, IntPtr.Zero, _location.X, _location.Y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSENDCHANGING);
+ }
- private void MoveToBottom(IntPtr handle)
+ public byte Opacity
+ {
+ get
{
- NativeMethods.SetWindowPos(handle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
+ return _opacity;
}
-
- private void MoveToTopMost(IntPtr handle)
+ set
{
- NativeMethods.SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
- }
-
- private CreateParams CreateParams
- {
- get
+ if (_opacity != value)
{
- CreateParams cp = new CreateParams
- {
- Width = 4096,
- Height = 4096,
- X = _location.X,
- Y = _location.Y,
- ExStyle = WS_EX_LAYERED | WS_EX_TOOLWINDOW
- };
-
- return cp;
+ _opacity = value;
+ BlendFunction blend = CreateBlendFunction();
+ NativeMethods.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, ref blend, ULW_ALPHA);
}
}
-
- protected override void WndProc(ref Message message)
- {
- switch (message.Msg)
- {
- case WM_COMMAND:
- {
- // need to dispatch the message for the context menu
- if (message.LParam == IntPtr.Zero)
- _commandDispatch.Invoke(null, new object[] {message.WParam.ToInt32() & 0xFFFF });
- }
- break;
- case WM_NCHITTEST:
- {
- message.Result = (IntPtr)HitResult.Caption;
- if (HitTest != null)
- {
- Point p = new Point(
- Macros.GET_X_LPARAM(message.LParam) - _location.X,
- Macros.GET_Y_LPARAM(message.LParam) - _location.Y
- );
- HitTestEventArgs e = new HitTestEventArgs(p, HitResult.Caption);
- HitTest(this, e);
- message.Result = (IntPtr)e.HitResult;
- }
- }
- break;
- case WM_NCLBUTTONDBLCLK:
- {
- MouseDoubleClick?.Invoke(this, new MouseEventArgs(MouseButtons.Left, 2, Macros.GET_X_LPARAM(message.LParam) - _location.X, Macros.GET_Y_LPARAM(message.LParam) - _location.Y, 0));
- message.Result = IntPtr.Zero;
- }
- break;
- case WM_NCRBUTTONDOWN:
- {
- message.Result = IntPtr.Zero;
- }
- break;
- case WM_NCRBUTTONUP:
- {
- ContextMenuStrip?.Show(new Point(Macros.GET_X_LPARAM(message.LParam), Macros.GET_Y_LPARAM(message.LParam)));
- message.Result = IntPtr.Zero;
- }
- break;
- case WM_WINDOWPOSCHANGING:
- {
- WINDOWPOS wp = (WINDOWPOS)Marshal.PtrToStructure(message.LParam, typeof(WINDOWPOS));
- if (!LockPositionAndSize)
- {
- // prevent the window from leaving the screen
- if ((wp.flags & SWP_NOMOVE) == 0)
- {
- Rectangle rect = Screen.GetWorkingArea(new Rectangle(wp.x, wp.y, wp.cx, wp.cy));
- const int margin = 16;
- wp.x = Math.Max(wp.x, rect.Left - wp.cx + margin);
- wp.x = Math.Min(wp.x, rect.Right - margin);
- wp.y = Math.Max(wp.y, rect.Top - wp.cy + margin);
- wp.y = Math.Min(wp.y, rect.Bottom - margin);
- }
-
- // update location and fire event
- if ((wp.flags & SWP_NOMOVE) == 0)
- {
- if (_location.X != wp.x || _location.Y != wp.y)
- {
- _location = new Point(wp.x, wp.y);
- LocationChanged?.Invoke(this, EventArgs.Empty);
- }
- }
-
- // update size and fire event
- if ((wp.flags & SWP_NOSIZE) == 0)
- {
- if (_size.Width != wp.cx || _size.Height != wp.cy)
- {
- _size = new Size(wp.cx, wp.cy);
- SizeChanged?.Invoke(this, EventArgs.Empty);
- }
- }
-
- // update the size of the layered window
- if ((wp.flags & SWP_NOSIZE) == 0)
- NativeMethods.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, ref _size, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero, 0);
-
- // update the position of the layered window
- if ((wp.flags & SWP_NOMOVE) == 0)
- NativeMethods.SetWindowPos(Handle, IntPtr.Zero, _location.X, _location.Y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSENDCHANGING);
- }
-
- // do not forward any move or size messages
- wp.flags |= SWP_NOSIZE | SWP_NOMOVE;
-
- // suppress any frame changed events
- wp.flags &= ~SWP_FRAMECHANGED;
-
- Marshal.StructureToPtr(wp, message.LParam, false);
- message.Result = IntPtr.Zero;
- }
- break;
- default:
- {
- base.WndProc(ref message);
- }
- break;
- }
- }
-
- private BlendFunction CreateBlendFunction()
- {
- return new BlendFunction { BlendOp = AC_SRC_OVER, BlendFlags = 0, SourceConstantAlpha = _opacity, AlphaFormat = AC_SRC_ALPHA };
- }
-
- private void CreateBuffer()
- {
- IntPtr handleScreenDC = NativeMethods.GetDC(IntPtr.Zero);
- _handleBitmapDC = NativeMethods.CreateCompatibleDC(handleScreenDC);
- NativeMethods.ReleaseDC(IntPtr.Zero, handleScreenDC);
- _bufferSize = _size;
-
- BITMAPINFO info = new BITMAPINFO();
- info.Size = Marshal.SizeOf(info);
- info.Width = _size.Width;
- info.Height = -_size.Height;
- info.BitCount = 32;
- info.Planes = 1;
-
- IntPtr hBmp = NativeMethods.CreateDIBSection(_handleBitmapDC, ref info, 0, out IntPtr _, IntPtr.Zero, 0);
- IntPtr hBmpOld = NativeMethods.SelectObject(_handleBitmapDC, hBmp);
- NativeMethods.DeleteObject(hBmpOld);
-
- _graphics = Graphics.FromHdc(_handleBitmapDC);
-
- if (Environment.OSVersion.Version.Major > 5)
- {
- _graphics.TextRenderingHint = TextRenderingHint.SystemDefault;
- _graphics.SmoothingMode = SmoothingMode.HighQuality;
- }
- }
-
- private void DisposeBuffer()
- {
- _graphics.Dispose();
- NativeMethods.DeleteDC(_handleBitmapDC);
- }
-
- public void Dispose()
- {
- DisposeBuffer();
- }
-
- public PaintEventHandler Paint;
-
- public void Redraw()
- {
- if (!_visible || Paint == null)
- return;
-
- if (_size != _bufferSize)
- {
- DisposeBuffer();
- CreateBuffer();
- }
-
- Paint(this, new PaintEventArgs(_graphics, new Rectangle(Point.Empty, _size)));
- Point pointSource = Point.Empty;
- BlendFunction blend = CreateBlendFunction();
- NativeMethods.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, ref _size, _handleBitmapDC, ref pointSource, 0, ref blend, ULW_ALPHA);
- // make sure the window is at the right location
- NativeMethods.SetWindowPos(Handle, IntPtr.Zero, _location.X, _location.Y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSENDCHANGING);
- }
-
- public byte Opacity
- {
- get
- {
- return _opacity;
- }
- set
- {
- if (_opacity != value)
- {
- _opacity = value;
- BlendFunction blend = CreateBlendFunction();
- NativeMethods.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, ref blend, ULW_ALPHA);
- }
- }
- }
-
- public bool Visible
- {
- get
- {
- return _visible;
- }
- set
- {
- if (_visible != value)
- {
- _visible = value;
- NativeMethods.SetWindowPos(Handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER | (value ? SWP_SHOWWINDOW : SWP_HIDEWINDOW));
-
- if (value)
- {
- if (!_alwaysOnTop)
- ShowDesktop.Instance.ShowDesktopChanged += ShowDesktopChanged;
- }
- else
- {
- if (!_alwaysOnTop)
- ShowDesktop.Instance.ShowDesktopChanged -= ShowDesktopChanged;
- }
- }
- }
- }
-
- // if locked, the window can not be moved or resized
- public bool LockPositionAndSize { get; set; }
-
- public bool AlwaysOnTop
- {
- get
- {
- return _alwaysOnTop;
- }
- set
- {
- if (value != _alwaysOnTop)
- {
- _alwaysOnTop = value;
-
- if (_alwaysOnTop)
- {
- if (_visible)
- ShowDesktop.Instance.ShowDesktopChanged -= ShowDesktopChanged;
-
- MoveToTopMost(Handle);
- }
- else
- {
- MoveToBottom(Handle);
-
- if (_visible)
- ShowDesktop.Instance.ShowDesktopChanged += ShowDesktopChanged;
- }
- }
- }
- }
-
- public Size Size
- {
- get
- {
- return _size;
- }
- set
- {
- if (_size != value)
- {
- _size = value;
- NativeMethods.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, ref _size, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero, 0);
- SizeChanged?.Invoke(this, EventArgs.Empty);
- }
- }
- }
-
- public Point Location
- {
- get
- {
- return _location;
- }
- set
- {
- if (_location != value)
- {
- _location = value;
- NativeMethods.SetWindowPos(Handle, IntPtr.Zero, _location.X, _location.Y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSENDCHANGING);
- LocationChanged?.Invoke(this, EventArgs.Empty);
- }
- }
- }
-
- public ContextMenuStrip ContextMenuStrip { get; set; }
-
- [StructLayout(LayoutKind.Sequential, Pack = 1)]
- private struct BlendFunction
- {
- public byte BlendOp;
- public byte BlendFlags;
- public byte SourceConstantAlpha;
- public byte AlphaFormat;
- }
-
- [StructLayout(LayoutKind.Sequential, Pack = 1)]
- private struct WINDOWPOS
- {
- public readonly IntPtr hwnd;
- public readonly IntPtr hwndInsertAfter;
- public int x;
- public int y;
- public readonly int cx;
- public readonly int cy;
- public uint flags;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public struct BITMAPINFO
- {
- public int Size;
- public int Width;
- public int Height;
- public short Planes;
- public short BitCount;
- public int Compression;
- public int SizeImage;
- public int XPelsPerMeter;
- public int YPelsPerMeter;
- public int ClrUsed;
- public int ClrImportant;
- public int Colors;
- }
-
- public static readonly IntPtr HWND_BOTTOM = (IntPtr)1;
- public static readonly IntPtr HWND_TOPMOST = (IntPtr)(-1);
-
- public const int WS_EX_LAYERED = 0x00080000;
- public const int WS_EX_TOOLWINDOW = 0x00000080;
-
- public const uint SWP_NOSIZE = 0x0001;
- public const uint SWP_NOMOVE = 0x0002;
- public const uint SWP_NOACTIVATE = 0x0010;
- public const uint SWP_FRAMECHANGED = 0x0020;
- public const uint SWP_HIDEWINDOW = 0x0080;
- public const uint SWP_SHOWWINDOW = 0x0040;
- public const uint SWP_NOZORDER = 0x0004;
- public const uint SWP_NOSENDCHANGING = 0x0400;
-
- public const int ULW_COLORKEY = 0x00000001;
- public const int ULW_ALPHA = 0x00000002;
- public const int ULW_OPAQUE = 0x00000004;
-
- public const byte AC_SRC_OVER = 0x00;
- public const byte AC_SRC_ALPHA = 0x01;
-
- public const int WM_NCHITTEST = 0x0084;
- public const int WM_NCLBUTTONDBLCLK = 0x00A3;
- public const int WM_NCLBUTTONDOWN = 0x00A1;
- public const int WM_NCLBUTTONUP = 0x00A2;
- public const int WM_NCRBUTTONDOWN = 0x00A4;
- public const int WM_NCRBUTTONUP = 0x00A5;
- public const int WM_WINDOWPOSCHANGING = 0x0046;
- public const int WM_COMMAND = 0x0111;
-
- public const int TPM_RIGHTBUTTON = 0x0002;
- public const int TPM_VERTICAL = 0x0040;
-
- private enum WindowAttribute : int
- {
- DWMWA_NCRENDERING_ENABLED = 1,
- DWMWA_NCRENDERING_POLICY,
- DWMWA_TRANSITIONS_FORCEDISABLED,
- DWMWA_ALLOW_NCPAINT,
- DWMWA_CAPTION_BUTTON_BOUNDS,
- DWMWA_NONCLIENT_RTL_LAYOUT,
- DWMWA_FORCE_ICONIC_REPRESENTATION,
- DWMWA_FLIP3D_POLICY,
- DWMWA_EXTENDED_FRAME_BOUNDS,
- DWMWA_HAS_ICONIC_BITMAP,
- DWMWA_DISALLOW_PEEK,
- DWMWA_EXCLUDED_FROM_PEEK,
- DWMWA_LAST
- }
-
- ///
- /// Some macros imported and converted from the Windows SDK
- ///
- private static class Macros
- {
- public static ushort LOWORD(IntPtr l)
- {
- return (ushort)((ulong)l & 0xFFFF);
- }
-
- public static ushort HIWORD(IntPtr l)
- {
- return (ushort)(((ulong)l >> 16) & 0xFFFF);
- }
-
- public static int GET_X_LPARAM(IntPtr lp)
- {
- return (short)LOWORD(lp);
- }
-
- public static int GET_Y_LPARAM(IntPtr lp)
- {
- return (short)HIWORD(lp);
- }
- }
-
- ///
- /// Imported native methods
- ///
- private static class NativeMethods
- {
- private const string USER = "user32.dll";
- private const string GDI = "gdi32.dll";
- private const string DWMAPI = "dwmapi.dll";
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, IntPtr pptDst, ref Size psize, IntPtr hdcSrc, IntPtr pprSrc, int crKey, IntPtr pblend, int dwFlags);
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, IntPtr pptDst, ref Size psize, IntPtr hdcSrc, ref Point pprSrc, int crKey, ref BlendFunction pblend, int dwFlags);
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, IntPtr pptDst, IntPtr psize, IntPtr hdcSrc, IntPtr pprSrc, int crKey, ref BlendFunction pblend, int dwFlags);
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- public static extern IntPtr GetDC(IntPtr hWnd);
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- public static extern bool TrackPopupMenuEx(IntPtr hMenu, uint uFlags, int x, int y, IntPtr hWnd, IntPtr tpmParams);
-
- [DllImport(GDI, CallingConvention = CallingConvention.Winapi)]
- public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
-
- [DllImport(GDI, CallingConvention = CallingConvention.Winapi)]
- public static extern IntPtr CreateDIBSection(IntPtr hdc, [In] ref BITMAPINFO pbmi, uint pila, out IntPtr ppvBits, IntPtr hSection, uint dwOffset);
-
- [DllImport(GDI, CallingConvention = CallingConvention.Winapi)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool DeleteDC(IntPtr hdc);
-
- [DllImport(GDI, CallingConvention = CallingConvention.Winapi)]
- public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
-
- [DllImport(GDI, CallingConvention = CallingConvention.Winapi)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool DeleteObject(IntPtr hObject);
-
- [DllImport(DWMAPI, CallingConvention = CallingConvention.Winapi)]
- public static extern int DwmSetWindowAttribute(IntPtr hwnd, WindowAttribute dwAttribute, ref bool pvAttribute, int cbAttribute);
- }
}
- public delegate void HitTestEventHandler(object sender, HitTestEventArgs e);
-
- public enum HitResult
+ public bool Visible
{
- Transparent = -1,
- Nowhere = 0,
- Client = 1,
- Caption = 2,
- Left = 10,
- Right = 11,
- Top = 12,
- TopLeft = 13,
- TopRight = 14,
- Bottom = 15,
- BottomLeft = 16,
- BottomRight = 17,
- Border = 18
+ get
+ {
+ return _visible;
+ }
+ set
+ {
+ if (_visible != value)
+ {
+ _visible = value;
+ NativeMethods.SetWindowPos(Handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER | (value ? SWP_SHOWWINDOW : SWP_HIDEWINDOW));
+
+ if (value)
+ {
+ if (!_alwaysOnTop)
+ ShowDesktop.Instance.ShowDesktopChanged += ShowDesktopChanged;
+ }
+ else
+ {
+ if (!_alwaysOnTop)
+ ShowDesktop.Instance.ShowDesktopChanged -= ShowDesktopChanged;
+ }
+ }
+ }
}
- public class HitTestEventArgs : EventArgs
+ // if locked, the window can not be moved or resized
+ public bool LockPositionAndSize { get; set; }
+
+ public bool AlwaysOnTop
{
- public HitTestEventArgs(Point location, HitResult hitResult)
+ get
{
- Location = location;
- HitResult = hitResult;
+ return _alwaysOnTop;
}
- public Point Location { get; }
- public HitResult HitResult { get; set; }
+ set
+ {
+ if (value != _alwaysOnTop)
+ {
+ _alwaysOnTop = value;
+
+ if (_alwaysOnTop)
+ {
+ if (_visible)
+ ShowDesktop.Instance.ShowDesktopChanged -= ShowDesktopChanged;
+
+ MoveToTopMost(Handle);
+ }
+ else
+ {
+ MoveToBottom(Handle);
+
+ if (_visible)
+ ShowDesktop.Instance.ShowDesktopChanged += ShowDesktopChanged;
+ }
+ }
+ }
+ }
+
+ public Size Size
+ {
+ get
+ {
+ return _size;
+ }
+ set
+ {
+ if (_size != value)
+ {
+ _size = value;
+ NativeMethods.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, ref _size, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero, 0);
+ SizeChanged?.Invoke(this, EventArgs.Empty);
+ }
+ }
+ }
+
+ public Point Location
+ {
+ get
+ {
+ return _location;
+ }
+ set
+ {
+ if (_location != value)
+ {
+ _location = value;
+ NativeMethods.SetWindowPos(Handle, IntPtr.Zero, _location.X, _location.Y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSENDCHANGING);
+ LocationChanged?.Invoke(this, EventArgs.Empty);
+ }
+ }
+ }
+
+ public ContextMenuStrip ContextMenuStrip { get; set; }
+
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ private struct BlendFunction
+ {
+ public byte BlendOp;
+ public byte BlendFlags;
+ public byte SourceConstantAlpha;
+ public byte AlphaFormat;
+ }
+
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
+ private struct WINDOWPOS
+ {
+ public readonly IntPtr hwnd;
+ public readonly IntPtr hwndInsertAfter;
+ public int x;
+ public int y;
+ public readonly int cx;
+ public readonly int cy;
+ public uint flags;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ public struct BITMAPINFO
+ {
+ public int Size;
+ public int Width;
+ public int Height;
+ public short Planes;
+ public short BitCount;
+ public int Compression;
+ public int SizeImage;
+ public int XPelsPerMeter;
+ public int YPelsPerMeter;
+ public int ClrUsed;
+ public int ClrImportant;
+ public int Colors;
+ }
+
+ public static readonly IntPtr HWND_BOTTOM = (IntPtr)1;
+ public static readonly IntPtr HWND_TOPMOST = (IntPtr)(-1);
+
+ public const int WS_EX_LAYERED = 0x00080000;
+ public const int WS_EX_TOOLWINDOW = 0x00000080;
+
+ public const uint SWP_NOSIZE = 0x0001;
+ public const uint SWP_NOMOVE = 0x0002;
+ public const uint SWP_NOACTIVATE = 0x0010;
+ public const uint SWP_FRAMECHANGED = 0x0020;
+ public const uint SWP_HIDEWINDOW = 0x0080;
+ public const uint SWP_SHOWWINDOW = 0x0040;
+ public const uint SWP_NOZORDER = 0x0004;
+ public const uint SWP_NOSENDCHANGING = 0x0400;
+
+ public const int ULW_COLORKEY = 0x00000001;
+ public const int ULW_ALPHA = 0x00000002;
+ public const int ULW_OPAQUE = 0x00000004;
+
+ public const byte AC_SRC_OVER = 0x00;
+ public const byte AC_SRC_ALPHA = 0x01;
+
+ public const int WM_NCHITTEST = 0x0084;
+ public const int WM_NCLBUTTONDBLCLK = 0x00A3;
+ public const int WM_NCLBUTTONDOWN = 0x00A1;
+ public const int WM_NCLBUTTONUP = 0x00A2;
+ public const int WM_NCRBUTTONDOWN = 0x00A4;
+ public const int WM_NCRBUTTONUP = 0x00A5;
+ public const int WM_WINDOWPOSCHANGING = 0x0046;
+ public const int WM_COMMAND = 0x0111;
+
+ public const int TPM_RIGHTBUTTON = 0x0002;
+ public const int TPM_VERTICAL = 0x0040;
+
+ private enum WindowAttribute : int
+ {
+ DWMWA_NCRENDERING_ENABLED = 1,
+ DWMWA_NCRENDERING_POLICY,
+ DWMWA_TRANSITIONS_FORCEDISABLED,
+ DWMWA_ALLOW_NCPAINT,
+ DWMWA_CAPTION_BUTTON_BOUNDS,
+ DWMWA_NONCLIENT_RTL_LAYOUT,
+ DWMWA_FORCE_ICONIC_REPRESENTATION,
+ DWMWA_FLIP3D_POLICY,
+ DWMWA_EXTENDED_FRAME_BOUNDS,
+ DWMWA_HAS_ICONIC_BITMAP,
+ DWMWA_DISALLOW_PEEK,
+ DWMWA_EXCLUDED_FROM_PEEK,
+ DWMWA_LAST
+ }
+
+ ///
+ /// Some macros imported and converted from the Windows SDK
+ ///
+ private static class Macros
+ {
+ public static ushort LOWORD(IntPtr l)
+ {
+ return (ushort)((ulong)l & 0xFFFF);
+ }
+
+ public static ushort HIWORD(IntPtr l)
+ {
+ return (ushort)(((ulong)l >> 16) & 0xFFFF);
+ }
+
+ public static int GET_X_LPARAM(IntPtr lp)
+ {
+ return (short)LOWORD(lp);
+ }
+
+ public static int GET_Y_LPARAM(IntPtr lp)
+ {
+ return (short)HIWORD(lp);
+ }
+ }
+
+ ///
+ /// Imported native methods
+ ///
+ private static class NativeMethods
+ {
+ private const string USER = "user32.dll";
+ private const string GDI = "gdi32.dll";
+ private const string DWMAPI = "dwmapi.dll";
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, IntPtr pptDst, ref Size psize, IntPtr hdcSrc, IntPtr pprSrc, int crKey, IntPtr pblend, int dwFlags);
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, IntPtr pptDst, ref Size psize, IntPtr hdcSrc, ref Point pprSrc, int crKey, ref BlendFunction pblend, int dwFlags);
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, IntPtr pptDst, IntPtr psize, IntPtr hdcSrc, IntPtr pprSrc, int crKey, ref BlendFunction pblend, int dwFlags);
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ public static extern IntPtr GetDC(IntPtr hWnd);
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ public static extern bool TrackPopupMenuEx(IntPtr hMenu, uint uFlags, int x, int y, IntPtr hWnd, IntPtr tpmParams);
+
+ [DllImport(GDI, CallingConvention = CallingConvention.Winapi)]
+ public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
+
+ [DllImport(GDI, CallingConvention = CallingConvention.Winapi)]
+ public static extern IntPtr CreateDIBSection(IntPtr hdc, [In] ref BITMAPINFO pbmi, uint pila, out IntPtr ppvBits, IntPtr hSection, uint dwOffset);
+
+ [DllImport(GDI, CallingConvention = CallingConvention.Winapi)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool DeleteDC(IntPtr hdc);
+
+ [DllImport(GDI, CallingConvention = CallingConvention.Winapi)]
+ public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
+
+ [DllImport(GDI, CallingConvention = CallingConvention.Winapi)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool DeleteObject(IntPtr hObject);
+
+ [DllImport(DWMAPI, CallingConvention = CallingConvention.Winapi)]
+ public static extern int DwmSetWindowAttribute(IntPtr hwnd, WindowAttribute dwAttribute, ref bool pvAttribute, int cbAttribute);
}
}
+
+public delegate void HitTestEventHandler(object sender, HitTestEventArgs e);
+
+public enum HitResult
+{
+ Transparent = -1,
+ Nowhere = 0,
+ Client = 1,
+ Caption = 2,
+ Left = 10,
+ Right = 11,
+ Top = 12,
+ TopLeft = 13,
+ TopRight = 14,
+ Bottom = 15,
+ BottomLeft = 16,
+ BottomRight = 17,
+ Border = 18
+}
+
+public class HitTestEventArgs : EventArgs
+{
+ public HitTestEventArgs(Point location, HitResult hitResult)
+ {
+ Location = location;
+ HitResult = hitResult;
+ }
+ public Point Location { get; }
+ public HitResult HitResult { get; set; }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/HardwareNode.cs b/LibreHardwareMonitor/UI/HardwareNode.cs
index fc2ed6c..86f3e11 100644
--- a/LibreHardwareMonitor/UI/HardwareNode.cs
+++ b/LibreHardwareMonitor/UI/HardwareNode.cs
@@ -10,149 +10,148 @@ using System;
using System.Collections.Generic;
using System.Text;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class HardwareNode : Node, IExpandPersistNode
{
- public class HardwareNode : Node, IExpandPersistNode
+ private readonly PersistentSettings _settings;
+ private readonly UnitManager _unitManager;
+ private readonly List _typeNodes = new List();
+ private readonly string _expandedIdentifier;
+ private bool _expanded;
+
+ public event EventHandler PlotSelectionChanged;
+
+ public HardwareNode(IHardware hardware, PersistentSettings settings, UnitManager unitManager)
{
- private readonly PersistentSettings _settings;
- private readonly UnitManager _unitManager;
- private readonly List _typeNodes = new List();
- private readonly string _expandedIdentifier;
- private bool _expanded;
+ _settings = settings;
+ _unitManager = unitManager;
+ _expandedIdentifier = new Identifier(hardware.Identifier, "expanded").ToString();
+ Hardware = hardware;
+ Image = HardwareTypeImage.Instance.GetImage(hardware.HardwareType);
- public event EventHandler PlotSelectionChanged;
+ foreach (SensorType sensorType in Enum.GetValues(typeof(SensorType)))
+ _typeNodes.Add(new TypeNode(sensorType, hardware.Identifier, _settings));
- public HardwareNode(IHardware hardware, PersistentSettings settings, UnitManager unitManager)
+ foreach (ISensor sensor in hardware.Sensors)
+ SensorAdded(sensor);
+
+ hardware.SensorAdded += SensorAdded;
+ hardware.SensorRemoved += SensorRemoved;
+
+ _expanded = settings.GetValue(_expandedIdentifier, true);
+ }
+
+
+ public override string Text
+ {
+ get { return Hardware.Name; }
+ set { Hardware.Name = value; }
+ }
+
+ public override string ToolTip
+ {
+ get
{
- _settings = settings;
- _unitManager = unitManager;
- _expandedIdentifier = new Identifier(hardware.Identifier, "expanded").ToString();
- Hardware = hardware;
- Image = HardwareTypeImage.Instance.GetImage(hardware.HardwareType);
+ IDictionary properties = Hardware.Properties;
- foreach (SensorType sensorType in Enum.GetValues(typeof(SensorType)))
- _typeNodes.Add(new TypeNode(sensorType, hardware.Identifier, _settings));
-
- foreach (ISensor sensor in hardware.Sensors)
- SensorAdded(sensor);
-
- hardware.SensorAdded += SensorAdded;
- hardware.SensorRemoved += SensorRemoved;
-
- _expanded = settings.GetValue(_expandedIdentifier, true);
- }
-
-
- public override string Text
- {
- get { return Hardware.Name; }
- set { Hardware.Name = value; }
- }
-
- public override string ToolTip
- {
- get
+ if (properties.Count > 0)
{
- IDictionary properties = Hardware.Properties;
-
- if (properties.Count > 0)
- {
- StringBuilder stringBuilder = new();
- stringBuilder.AppendLine("Hardware properties:");
+ StringBuilder stringBuilder = new();
+ stringBuilder.AppendLine("Hardware properties:");
- foreach (KeyValuePair property in properties)
- stringBuilder.AppendFormat(" • {0}: {1}\n", property.Key, property.Value);
+ foreach (KeyValuePair property in properties)
+ stringBuilder.AppendFormat(" • {0}: {1}\n", property.Key, property.Value);
- return stringBuilder.ToString();
- }
+ return stringBuilder.ToString();
+ }
- return null;
+ return null;
+ }
+ }
+
+ public IHardware Hardware { get; }
+
+ public bool Expanded
+ {
+ get => _expanded;
+ set
+ {
+ _expanded = value;
+ _settings.SetValue(_expandedIdentifier, _expanded);
+ }
+ }
+
+ private void UpdateNode(TypeNode node)
+ {
+ if (node.Nodes.Count > 0)
+ {
+ if (!Nodes.Contains(node))
+ {
+ int i = 0;
+ while (i < Nodes.Count && ((TypeNode)Nodes[i]).SensorType < node.SensorType)
+ i++;
+
+ Nodes.Insert(i, node);
}
}
-
- public IHardware Hardware { get; }
-
- public bool Expanded
+ else
{
- get => _expanded;
- set
- {
- _expanded = value;
- _settings.SetValue(_expandedIdentifier, _expanded);
- }
+ if (Nodes.Contains(node))
+ Nodes.Remove(node);
}
+ }
- private void UpdateNode(TypeNode node)
+ private void SensorRemoved(ISensor sensor)
+ {
+ foreach (TypeNode typeNode in _typeNodes)
{
- if (node.Nodes.Count > 0)
+ if (typeNode.SensorType == sensor.SensorType)
{
- if (!Nodes.Contains(node))
+ SensorNode sensorNode = null;
+ foreach (Node node in typeNode.Nodes)
{
- int i = 0;
- while (i < Nodes.Count && ((TypeNode)Nodes[i]).SensorType < node.SensorType)
- i++;
-
- Nodes.Insert(i, node);
+ if (node is SensorNode n && n.Sensor == sensor)
+ sensorNode = n;
}
- }
- else
- {
- if (Nodes.Contains(node))
- Nodes.Remove(node);
- }
- }
-
- private void SensorRemoved(ISensor sensor)
- {
- foreach (TypeNode typeNode in _typeNodes)
- {
- if (typeNode.SensorType == sensor.SensorType)
+ if (sensorNode != null)
{
- SensorNode sensorNode = null;
- foreach (Node node in typeNode.Nodes)
- {
- if (node is SensorNode n && n.Sensor == sensor)
- sensorNode = n;
- }
- if (sensorNode != null)
- {
- sensorNode.PlotSelectionChanged -= SensorPlotSelectionChanged;
- typeNode.Nodes.Remove(sensorNode);
- UpdateNode(typeNode);
- }
- }
- }
- PlotSelectionChanged?.Invoke(this, null);
- }
-
- private void InsertSorted(Node node, ISensor sensor)
- {
- int i = 0;
- while (i < node.Nodes.Count && ((SensorNode)node.Nodes[i]).Sensor.Index < sensor.Index)
- i++;
-
- SensorNode sensorNode = new SensorNode(sensor, _settings, _unitManager);
- sensorNode.PlotSelectionChanged += SensorPlotSelectionChanged;
- node.Nodes.Insert(i, sensorNode);
- }
-
- private void SensorPlotSelectionChanged(object sender, EventArgs e)
- {
- PlotSelectionChanged?.Invoke(this, null);
- }
-
- private void SensorAdded(ISensor sensor)
- {
- foreach (TypeNode typeNode in _typeNodes)
- {
- if (typeNode.SensorType == sensor.SensorType)
- {
- InsertSorted(typeNode, sensor);
+ sensorNode.PlotSelectionChanged -= SensorPlotSelectionChanged;
+ typeNode.Nodes.Remove(sensorNode);
UpdateNode(typeNode);
}
}
-
- PlotSelectionChanged?.Invoke(this, null);
}
+ PlotSelectionChanged?.Invoke(this, null);
}
-}
+
+ private void InsertSorted(Node node, ISensor sensor)
+ {
+ int i = 0;
+ while (i < node.Nodes.Count && ((SensorNode)node.Nodes[i]).Sensor.Index < sensor.Index)
+ i++;
+
+ SensorNode sensorNode = new SensorNode(sensor, _settings, _unitManager);
+ sensorNode.PlotSelectionChanged += SensorPlotSelectionChanged;
+ node.Nodes.Insert(i, sensorNode);
+ }
+
+ private void SensorPlotSelectionChanged(object sender, EventArgs e)
+ {
+ PlotSelectionChanged?.Invoke(this, null);
+ }
+
+ private void SensorAdded(ISensor sensor)
+ {
+ foreach (TypeNode typeNode in _typeNodes)
+ {
+ if (typeNode.SensorType == sensor.SensorType)
+ {
+ InsertSorted(typeNode, sensor);
+ UpdateNode(typeNode);
+ }
+ }
+
+ PlotSelectionChanged?.Invoke(this, null);
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/HardwareTypeImage.cs b/LibreHardwareMonitor/UI/HardwareTypeImage.cs
index 7e947ef..0f8b8fc 100644
--- a/LibreHardwareMonitor/UI/HardwareTypeImage.cs
+++ b/LibreHardwareMonitor/UI/HardwareTypeImage.cs
@@ -8,67 +8,66 @@ using System.Drawing;
using System.Collections.Generic;
using LibreHardwareMonitor.Hardware;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class HardwareTypeImage
{
- public class HardwareTypeImage
+ private readonly IDictionary _images = new Dictionary();
+
+ private HardwareTypeImage() { }
+
+ public static HardwareTypeImage Instance { get; } = new HardwareTypeImage();
+
+ public Image GetImage(HardwareType hardwareType)
{
- private readonly IDictionary _images = new Dictionary();
-
- private HardwareTypeImage() { }
-
- public static HardwareTypeImage Instance { get; } = new HardwareTypeImage();
-
- public Image GetImage(HardwareType hardwareType)
- {
- if (_images.TryGetValue(hardwareType, out Image image))
- return image;
-
-
- switch (hardwareType)
- {
- case HardwareType.Cpu:
- image = Utilities.EmbeddedResources.GetImage("cpu.png");
- break;
- case HardwareType.GpuNvidia:
- image = Utilities.EmbeddedResources.GetImage("nvidia.png");
- break;
- case HardwareType.GpuAmd:
- image = Utilities.EmbeddedResources.GetImage("amd.png");
- break;
- case HardwareType.GpuIntel:
- image = Utilities.EmbeddedResources.GetImage("intel.png");
- break;
- case HardwareType.Storage:
- image = Utilities.EmbeddedResources.GetImage("hdd.png");
- break;
- case HardwareType.Motherboard:
- image = Utilities.EmbeddedResources.GetImage("mainboard.png");
- break;
- case HardwareType.SuperIO:
- case HardwareType.EmbeddedController:
- image = Utilities.EmbeddedResources.GetImage("chip.png");
- break;
- case HardwareType.Memory:
- image = Utilities.EmbeddedResources.GetImage("ram.png");
- break;
- case HardwareType.Network:
- image = Utilities.EmbeddedResources.GetImage("nic.png");
- break;
- case HardwareType.Cooler:
- image = Utilities.EmbeddedResources.GetImage("fan.png");
- break;
- case HardwareType.Psu:
- image = Utilities.EmbeddedResources.GetImage("power-supply.png");
- break;
- case HardwareType.Battery:
- image = Utilities.EmbeddedResources.GetImage("battery.png");
- break;
- default:
- image = new Bitmap(1, 1);
- break;
- }
- _images.Add(hardwareType, image);
+ if (_images.TryGetValue(hardwareType, out Image image))
return image;
+
+
+ switch (hardwareType)
+ {
+ case HardwareType.Cpu:
+ image = Utilities.EmbeddedResources.GetImage("cpu.png");
+ break;
+ case HardwareType.GpuNvidia:
+ image = Utilities.EmbeddedResources.GetImage("nvidia.png");
+ break;
+ case HardwareType.GpuAmd:
+ image = Utilities.EmbeddedResources.GetImage("amd.png");
+ break;
+ case HardwareType.GpuIntel:
+ image = Utilities.EmbeddedResources.GetImage("intel.png");
+ break;
+ case HardwareType.Storage:
+ image = Utilities.EmbeddedResources.GetImage("hdd.png");
+ break;
+ case HardwareType.Motherboard:
+ image = Utilities.EmbeddedResources.GetImage("mainboard.png");
+ break;
+ case HardwareType.SuperIO:
+ case HardwareType.EmbeddedController:
+ image = Utilities.EmbeddedResources.GetImage("chip.png");
+ break;
+ case HardwareType.Memory:
+ image = Utilities.EmbeddedResources.GetImage("ram.png");
+ break;
+ case HardwareType.Network:
+ image = Utilities.EmbeddedResources.GetImage("nic.png");
+ break;
+ case HardwareType.Cooler:
+ image = Utilities.EmbeddedResources.GetImage("fan.png");
+ break;
+ case HardwareType.Psu:
+ image = Utilities.EmbeddedResources.GetImage("power-supply.png");
+ break;
+ case HardwareType.Battery:
+ image = Utilities.EmbeddedResources.GetImage("battery.png");
+ break;
+ default:
+ image = new Bitmap(1, 1);
+ break;
}
+ _images.Add(hardwareType, image);
+ return image;
}
-}
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/IExpandPersistNode.cs b/LibreHardwareMonitor/UI/IExpandPersistNode.cs
index 63c0441..63b433b 100644
--- a/LibreHardwareMonitor/UI/IExpandPersistNode.cs
+++ b/LibreHardwareMonitor/UI/IExpandPersistNode.cs
@@ -1,7 +1,6 @@
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public interface IExpandPersistNode
{
- public interface IExpandPersistNode
- {
- bool Expanded { get; set; }
- }
-}
+ bool Expanded { get; set; }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/MainForm.cs b/LibreHardwareMonitor/UI/MainForm.cs
index 6c3ee79..3d7c4d9 100644
--- a/LibreHardwareMonitor/UI/MainForm.cs
+++ b/LibreHardwareMonitor/UI/MainForm.cs
@@ -17,1096 +17,1095 @@ using LibreHardwareMonitor.Hardware;
using LibreHardwareMonitor.Utilities;
using LibreHardwareMonitor.Wmi;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public sealed partial class MainForm : Form
{
- public sealed partial class MainForm : Form
+ private readonly UserOption _autoStart;
+ private readonly Computer _computer;
+ private readonly SensorGadget _gadget;
+ private readonly Logger _logger;
+ private readonly UserRadioGroup _loggingInterval;
+ private readonly UserOption _logSensors;
+ private readonly UserOption _minimizeOnClose;
+ private readonly UserOption _minimizeToTray;
+ private readonly Color[] _plotColorPalette;
+ private readonly PlotPanel _plotPanel;
+ private readonly UserOption _readBatterySensors;
+ private readonly UserOption _readCpuSensors;
+ private readonly UserOption _readFanControllersSensors;
+ private readonly UserOption _readGpuSensors;
+ private readonly UserOption _readHddSensors;
+ private readonly UserOption _readMainboardSensors;
+ private readonly UserOption _readNicSensors;
+ private readonly UserOption _readPsuSensors;
+ private readonly UserOption _readRamSensors;
+ private readonly Node _root;
+ private readonly UserOption _runWebServer;
+ private readonly UserRadioGroup _sensorValuesTimeWindow;
+ private readonly PersistentSettings _settings;
+ private readonly UserOption _showGadget;
+ private readonly StartupManager _startupManager = new();
+ private readonly SystemTray _systemTray;
+ private readonly UnitManager _unitManager;
+ private readonly UpdateVisitor _updateVisitor = new();
+ private readonly WmiProvider _wmiProvider;
+
+ private int _delayCount;
+ private Form _plotForm;
+ private UserRadioGroup _plotLocation;
+ private bool _selectionDragging;
+ private IDictionary _sensorPlotColors = new Dictionary();
+ private UserOption _showPlot;
+
+ public MainForm()
{
- private readonly UserOption _autoStart;
- private readonly Computer _computer;
- private readonly SensorGadget _gadget;
- private readonly Logger _logger;
- private readonly UserRadioGroup _loggingInterval;
- private readonly UserOption _logSensors;
- private readonly UserOption _minimizeOnClose;
- private readonly UserOption _minimizeToTray;
- private readonly Color[] _plotColorPalette;
- private readonly PlotPanel _plotPanel;
- private readonly UserOption _readBatterySensors;
- private readonly UserOption _readCpuSensors;
- private readonly UserOption _readFanControllersSensors;
- private readonly UserOption _readGpuSensors;
- private readonly UserOption _readHddSensors;
- private readonly UserOption _readMainboardSensors;
- private readonly UserOption _readNicSensors;
- private readonly UserOption _readPsuSensors;
- private readonly UserOption _readRamSensors;
- private readonly Node _root;
- private readonly UserOption _runWebServer;
- private readonly UserRadioGroup _sensorValuesTimeWindow;
- private readonly PersistentSettings _settings;
- private readonly UserOption _showGadget;
- private readonly StartupManager _startupManager = new();
- private readonly SystemTray _systemTray;
- private readonly UnitManager _unitManager;
- private readonly UpdateVisitor _updateVisitor = new();
- private readonly WmiProvider _wmiProvider;
+ InitializeComponent();
- private int _delayCount;
- private Form _plotForm;
- private UserRadioGroup _plotLocation;
- private bool _selectionDragging;
- private IDictionary _sensorPlotColors = new Dictionary();
- private UserOption _showPlot;
+ _settings = new PersistentSettings();
+ _settings.Load(Path.ChangeExtension(Application.ExecutablePath, ".config"));
- public MainForm()
+ _unitManager = new UnitManager(_settings);
+
+ // make sure the buffers used for double buffering are not disposed
+ // after each draw call
+ BufferedGraphicsManager.Current.MaximumBuffer = Screen.PrimaryScreen.Bounds.Size;
+
+ // set the DockStyle here, to avoid conflicts with the MainMenu
+ splitContainer.Dock = DockStyle.Fill;
+
+ Font = SystemFonts.MessageBoxFont;
+ treeView.Font = SystemFonts.MessageBoxFont;
+
+ // Set the bounds immediately, so that our child components can be
+ // properly placed.
+ Bounds = new Rectangle
{
- InitializeComponent();
+ X = _settings.GetValue("mainForm.Location.X", Location.X),
+ Y = _settings.GetValue("mainForm.Location.Y", Location.Y),
+ Width = _settings.GetValue("mainForm.Width", 470),
+ Height = _settings.GetValue("mainForm.Height", 640)
+ };
- _settings = new PersistentSettings();
- _settings.Load(Path.ChangeExtension(Application.ExecutablePath, ".config"));
+ _plotPanel = new PlotPanel(_settings, _unitManager) { Font = SystemFonts.MessageBoxFont, Dock = DockStyle.Fill };
- _unitManager = new UnitManager(_settings);
+ nodeCheckBox.IsVisibleValueNeeded += NodeCheckBox_IsVisibleValueNeeded;
+ nodeTextBoxText.DrawText += NodeTextBoxText_DrawText;
+ nodeTextBoxValue.DrawText += NodeTextBoxText_DrawText;
+ nodeTextBoxMin.DrawText += NodeTextBoxText_DrawText;
+ nodeTextBoxMax.DrawText += NodeTextBoxText_DrawText;
+ nodeTextBoxText.EditorShowing += NodeTextBoxText_EditorShowing;
- // make sure the buffers used for double buffering are not disposed
- // after each draw call
- BufferedGraphicsManager.Current.MaximumBuffer = Screen.PrimaryScreen.Bounds.Size;
+ foreach (TreeColumn column in treeView.Columns)
+ column.Width = Math.Max(20, Math.Min(400, _settings.GetValue("treeView.Columns." + column.Header + ".Width", column.Width)));
- // set the DockStyle here, to avoid conflicts with the MainMenu
- splitContainer.Dock = DockStyle.Fill;
+ TreeModel treeModel = new();
+ _root = new Node(Environment.MachineName) { Image = EmbeddedResources.GetImage("computer.png") };
- Font = SystemFonts.MessageBoxFont;
- treeView.Font = SystemFonts.MessageBoxFont;
+ treeModel.Nodes.Add(_root);
+ treeView.Model = treeModel;
- // Set the bounds immediately, so that our child components can be
- // properly placed.
- Bounds = new Rectangle
- {
- X = _settings.GetValue("mainForm.Location.X", Location.X),
- Y = _settings.GetValue("mainForm.Location.Y", Location.Y),
- Width = _settings.GetValue("mainForm.Width", 470),
- Height = _settings.GetValue("mainForm.Height", 640)
- };
+ _computer = new Computer(_settings);
- _plotPanel = new PlotPanel(_settings, _unitManager) { Font = SystemFonts.MessageBoxFont, Dock = DockStyle.Fill };
+ _systemTray = new SystemTray(_computer, _settings, _unitManager);
+ _systemTray.HideShowCommand += HideShowClick;
+ _systemTray.ExitCommand += ExitClick;
- nodeCheckBox.IsVisibleValueNeeded += NodeCheckBox_IsVisibleValueNeeded;
- nodeTextBoxText.DrawText += NodeTextBoxText_DrawText;
- nodeTextBoxValue.DrawText += NodeTextBoxText_DrawText;
- nodeTextBoxMin.DrawText += NodeTextBoxText_DrawText;
- nodeTextBoxMax.DrawText += NodeTextBoxText_DrawText;
- nodeTextBoxText.EditorShowing += NodeTextBoxText_EditorShowing;
-
- foreach (TreeColumn column in treeView.Columns)
- column.Width = Math.Max(20, Math.Min(400, _settings.GetValue("treeView.Columns." + column.Header + ".Width", column.Width)));
-
- TreeModel treeModel = new();
- _root = new Node(Environment.MachineName) { Image = EmbeddedResources.GetImage("computer.png") };
-
- treeModel.Nodes.Add(_root);
- treeView.Model = treeModel;
-
- _computer = new Computer(_settings);
-
- _systemTray = new SystemTray(_computer, _settings, _unitManager);
- _systemTray.HideShowCommand += HideShowClick;
- _systemTray.ExitCommand += ExitClick;
-
- if (Software.OperatingSystem.IsUnix)
- {
- // Unix
- treeView.RowHeight = Math.Max(treeView.RowHeight, 18);
- splitContainer.BorderStyle = BorderStyle.None;
- splitContainer.Border3DStyle = Border3DStyle.Adjust;
- splitContainer.SplitterWidth = 4;
- treeView.BorderStyle = BorderStyle.Fixed3D;
- _plotPanel.BorderStyle = BorderStyle.Fixed3D;
- gadgetMenuItem.Visible = false;
- minCloseMenuItem.Visible = false;
- minTrayMenuItem.Visible = false;
- startMinMenuItem.Visible = false;
- }
- else
- {
- // Windows
- treeView.RowHeight = Math.Max(treeView.Font.Height + 1, 18);
- _gadget = new SensorGadget(_computer, _settings, _unitManager);
- _gadget.HideShowCommand += HideShowClick;
- _wmiProvider = new WmiProvider(_computer);
- }
-
- treeView.ShowNodeToolTips = true;
- NodeToolTipProvider tooltipProvider = new();
- nodeTextBoxText.ToolTipProvider = tooltipProvider;
- nodeTextBoxValue.ToolTipProvider = tooltipProvider;
- _logger = new Logger(_computer);
-
- _plotColorPalette = new Color[13];
- _plotColorPalette[0] = Color.Blue;
- _plotColorPalette[1] = Color.OrangeRed;
- _plotColorPalette[2] = Color.Green;
- _plotColorPalette[3] = Color.LightSeaGreen;
- _plotColorPalette[4] = Color.Goldenrod;
- _plotColorPalette[5] = Color.DarkViolet;
- _plotColorPalette[6] = Color.YellowGreen;
- _plotColorPalette[7] = Color.SaddleBrown;
- _plotColorPalette[8] = Color.RoyalBlue;
- _plotColorPalette[9] = Color.DeepPink;
- _plotColorPalette[10] = Color.MediumSeaGreen;
- _plotColorPalette[11] = Color.Olive;
- _plotColorPalette[12] = Color.Firebrick;
-
- _computer.HardwareAdded += HardwareAdded;
- _computer.HardwareRemoved += HardwareRemoved;
- _computer.Open();
-
- backgroundUpdater.DoWork += BackgroundUpdater_DoWork;
- timer.Enabled = true;
-
- UserOption showHiddenSensors = new("hiddenMenuItem", false, hiddenMenuItem, _settings);
- showHiddenSensors.Changed += delegate { treeModel.ForceVisible = showHiddenSensors.Value; };
-
- UserOption showValue = new("valueMenuItem", true, valueMenuItem, _settings);
- showValue.Changed += delegate { treeView.Columns[1].IsVisible = showValue.Value; };
-
- UserOption showMin = new("minMenuItem", false, minMenuItem, _settings);
- showMin.Changed += delegate { treeView.Columns[2].IsVisible = showMin.Value; };
-
- UserOption showMax = new("maxMenuItem", true, maxMenuItem, _settings);
- showMax.Changed += delegate { treeView.Columns[3].IsVisible = showMax.Value; };
-
- var _ = new UserOption("startMinMenuItem", false, startMinMenuItem, _settings);
- _minimizeToTray = new UserOption("minTrayMenuItem", true, minTrayMenuItem, _settings);
- _minimizeToTray.Changed += delegate { _systemTray.IsMainIconEnabled = _minimizeToTray.Value; };
-
- _minimizeOnClose = new UserOption("minCloseMenuItem", false, minCloseMenuItem, _settings);
-
- _autoStart = new UserOption(null, _startupManager.Startup, startupMenuItem, _settings);
- _autoStart.Changed += delegate
- {
- try
- {
- _startupManager.Startup = _autoStart.Value;
- }
- catch (InvalidOperationException)
- {
- MessageBox.Show("Updating the auto-startup option failed.",
- "Error",
- MessageBoxButtons.OK,
- MessageBoxIcon.Error);
-
- _autoStart.Value = _startupManager.Startup;
- }
- };
-
- _readMainboardSensors = new UserOption("mainboardMenuItem", true, mainboardMenuItem, _settings);
- _readMainboardSensors.Changed += delegate { _computer.IsMotherboardEnabled = _readMainboardSensors.Value; };
-
- _readCpuSensors = new UserOption("cpuMenuItem", true, cpuMenuItem, _settings);
- _readCpuSensors.Changed += delegate { _computer.IsCpuEnabled = _readCpuSensors.Value; };
-
- _readRamSensors = new UserOption("ramMenuItem", true, ramMenuItem, _settings);
- _readRamSensors.Changed += delegate { _computer.IsMemoryEnabled = _readRamSensors.Value; };
-
- _readGpuSensors = new UserOption("gpuMenuItem", true, gpuMenuItem, _settings);
- _readGpuSensors.Changed += delegate { _computer.IsGpuEnabled = _readGpuSensors.Value; };
-
- _readFanControllersSensors = new UserOption("fanControllerMenuItem", true, fanControllerMenuItem, _settings);
- _readFanControllersSensors.Changed += delegate { _computer.IsControllerEnabled = _readFanControllersSensors.Value; };
-
- _readHddSensors = new UserOption("hddMenuItem", true, hddMenuItem, _settings);
- _readHddSensors.Changed += delegate { _computer.IsStorageEnabled = _readHddSensors.Value; };
-
- _readNicSensors = new UserOption("nicMenuItem", true, nicMenuItem, _settings);
- _readNicSensors.Changed += delegate { _computer.IsNetworkEnabled = _readNicSensors.Value; };
-
- _readPsuSensors = new UserOption("psuMenuItem", true, psuMenuItem, _settings);
- _readPsuSensors.Changed += delegate { _computer.IsPsuEnabled = _readPsuSensors.Value; };
-
- _readBatterySensors = new UserOption("batteryMenuItem", true, batteryMenuItem, _settings);
- _readBatterySensors.Changed += delegate { _computer.IsBatteryEnabled = _readBatterySensors.Value; };
-
- _showGadget = new UserOption("gadgetMenuItem", false, gadgetMenuItem, _settings);
- _showGadget.Changed += delegate
- {
- if (_gadget != null)
- _gadget.Visible = _showGadget.Value;
- };
-
- celsiusMenuItem.Checked = _unitManager.TemperatureUnit == TemperatureUnit.Celsius;
- fahrenheitMenuItem.Checked = !celsiusMenuItem.Checked;
-
- Server = new HttpServer(_root,
- _settings.GetValue("listenerPort", 8085),
- _settings.GetValue("authenticationEnabled", false),
- _settings.GetValue("authenticationUserName", ""),
- _settings.GetValue("authenticationPassword", ""));
-
- if (Server.PlatformNotSupported)
- {
- webMenuItemSeparator.Visible = false;
- webMenuItem.Visible = false;
- }
-
- _runWebServer = new UserOption("runWebServerMenuItem", false, runWebServerMenuItem, _settings);
- _runWebServer.Changed += delegate
- {
- if (_runWebServer.Value)
- Server.StartHttpListener();
- else
- Server.StopHttpListener();
- };
-
- authWebServerMenuItem.Checked = _settings.GetValue("authenticationEnabled", false);
-
- _logSensors = new UserOption("logSensorsMenuItem", false, logSensorsMenuItem, _settings);
-
- _loggingInterval = new UserRadioGroup("loggingInterval",
- 0,
- new[]
- {
- log1sMenuItem,
- log2sMenuItem,
- log5sMenuItem,
- log10sMenuItem,
- log30sMenuItem,
- log1minMenuItem,
- log2minMenuItem,
- log5minMenuItem,
- log10minMenuItem,
- log30minMenuItem,
- log1hMenuItem,
- log2hMenuItem,
- log6hMenuItem
- },
- _settings);
-
- _loggingInterval.Changed += (sender, e) =>
- {
- switch (_loggingInterval.Value)
- {
- case 0:
- _logger.LoggingInterval = new TimeSpan(0, 0, 1);
- break;
- case 1:
- _logger.LoggingInterval = new TimeSpan(0, 0, 2);
- break;
- case 2:
- _logger.LoggingInterval = new TimeSpan(0, 0, 5);
- break;
- case 3:
- _logger.LoggingInterval = new TimeSpan(0, 0, 10);
- break;
- case 4:
- _logger.LoggingInterval = new TimeSpan(0, 0, 30);
- break;
- case 5:
- _logger.LoggingInterval = new TimeSpan(0, 1, 0);
- break;
- case 6:
- _logger.LoggingInterval = new TimeSpan(0, 2, 0);
- break;
- case 7:
- _logger.LoggingInterval = new TimeSpan(0, 5, 0);
- break;
- case 8:
- _logger.LoggingInterval = new TimeSpan(0, 10, 0);
- break;
- case 9:
- _logger.LoggingInterval = new TimeSpan(0, 30, 0);
- break;
- case 10:
- _logger.LoggingInterval = new TimeSpan(1, 0, 0);
- break;
- case 11:
- _logger.LoggingInterval = new TimeSpan(2, 0, 0);
- break;
- case 12:
- _logger.LoggingInterval = new TimeSpan(6, 0, 0);
- break;
- }
- };
-
- _sensorValuesTimeWindow = new UserRadioGroup("sensorValuesTimeWindow",
- 10,
- new[]
- {
- timeWindow30sMenuItem,
- timeWindow1minMenuItem,
- timeWindow2minMenuItem,
- timeWindow5minMenuItem,
- timeWindow10minMenuItem,
- timeWindow30minMenuItem,
- timeWindow1hMenuItem,
- timeWindow2hMenuItem,
- timeWindow6hMenuItem,
- timeWindow12hMenuItem,
- timeWindow24hMenuItem
- },
- _settings);
-
- _sensorValuesTimeWindow.Changed += (sender, e) =>
- {
- TimeSpan timeWindow = TimeSpan.Zero;
- switch (_sensorValuesTimeWindow.Value)
- {
- case 0:
- timeWindow = new TimeSpan(0, 0, 30);
- break;
- case 1:
- timeWindow = new TimeSpan(0, 1, 0);
- break;
- case 2:
- timeWindow = new TimeSpan(0, 2, 0);
- break;
- case 3:
- timeWindow = new TimeSpan(0, 5, 0);
- break;
- case 4:
- timeWindow = new TimeSpan(0, 10, 0);
- break;
- case 5:
- timeWindow = new TimeSpan(0, 30, 0);
- break;
- case 6:
- timeWindow = new TimeSpan(1, 0, 0);
- break;
- case 7:
- timeWindow = new TimeSpan(2, 0, 0);
- break;
- case 8:
- timeWindow = new TimeSpan(6, 0, 0);
- break;
- case 9:
- timeWindow = new TimeSpan(12, 0, 0);
- break;
- case 10:
- timeWindow = new TimeSpan(24, 0, 0);
- break;
- }
-
- _computer.Accept(new SensorVisitor(delegate(ISensor sensor) { sensor.ValuesTimeWindow = timeWindow; }));
- };
-
- InitializePlotForm();
- InitializeSplitter();
-
- startupMenuItem.Visible = _startupManager.IsAvailable;
-
- if (startMinMenuItem.Checked)
- {
- if (!minTrayMenuItem.Checked)
- {
- WindowState = FormWindowState.Minimized;
- Show();
- }
- }
- else
- {
- Show();
- }
-
- // Create a handle, otherwise calling Close() does not fire FormClosed
-
- // Make sure the settings are saved when the user logs off
- Microsoft.Win32.SystemEvents.SessionEnded += delegate
- {
- _computer.Close();
- SaveConfiguration();
- if (_runWebServer.Value)
- Server.Quit();
- };
-
- Microsoft.Win32.SystemEvents.PowerModeChanged += PowerModeChanged;
+ if (Software.OperatingSystem.IsUnix)
+ {
+ // Unix
+ treeView.RowHeight = Math.Max(treeView.RowHeight, 18);
+ splitContainer.BorderStyle = BorderStyle.None;
+ splitContainer.Border3DStyle = Border3DStyle.Adjust;
+ splitContainer.SplitterWidth = 4;
+ treeView.BorderStyle = BorderStyle.Fixed3D;
+ _plotPanel.BorderStyle = BorderStyle.Fixed3D;
+ gadgetMenuItem.Visible = false;
+ minCloseMenuItem.Visible = false;
+ minTrayMenuItem.Visible = false;
+ startMinMenuItem.Visible = false;
+ }
+ else
+ {
+ // Windows
+ treeView.RowHeight = Math.Max(treeView.Font.Height + 1, 18);
+ _gadget = new SensorGadget(_computer, _settings, _unitManager);
+ _gadget.HideShowCommand += HideShowClick;
+ _wmiProvider = new WmiProvider(_computer);
}
- public bool AuthWebServerMenuItemChecked
+ treeView.ShowNodeToolTips = true;
+ NodeToolTipProvider tooltipProvider = new();
+ nodeTextBoxText.ToolTipProvider = tooltipProvider;
+ nodeTextBoxValue.ToolTipProvider = tooltipProvider;
+ _logger = new Logger(_computer);
+
+ _plotColorPalette = new Color[13];
+ _plotColorPalette[0] = Color.Blue;
+ _plotColorPalette[1] = Color.OrangeRed;
+ _plotColorPalette[2] = Color.Green;
+ _plotColorPalette[3] = Color.LightSeaGreen;
+ _plotColorPalette[4] = Color.Goldenrod;
+ _plotColorPalette[5] = Color.DarkViolet;
+ _plotColorPalette[6] = Color.YellowGreen;
+ _plotColorPalette[7] = Color.SaddleBrown;
+ _plotColorPalette[8] = Color.RoyalBlue;
+ _plotColorPalette[9] = Color.DeepPink;
+ _plotColorPalette[10] = Color.MediumSeaGreen;
+ _plotColorPalette[11] = Color.Olive;
+ _plotColorPalette[12] = Color.Firebrick;
+
+ _computer.HardwareAdded += HardwareAdded;
+ _computer.HardwareRemoved += HardwareRemoved;
+ _computer.Open();
+
+ backgroundUpdater.DoWork += BackgroundUpdater_DoWork;
+ timer.Enabled = true;
+
+ UserOption showHiddenSensors = new("hiddenMenuItem", false, hiddenMenuItem, _settings);
+ showHiddenSensors.Changed += delegate { treeModel.ForceVisible = showHiddenSensors.Value; };
+
+ UserOption showValue = new("valueMenuItem", true, valueMenuItem, _settings);
+ showValue.Changed += delegate { treeView.Columns[1].IsVisible = showValue.Value; };
+
+ UserOption showMin = new("minMenuItem", false, minMenuItem, _settings);
+ showMin.Changed += delegate { treeView.Columns[2].IsVisible = showMin.Value; };
+
+ UserOption showMax = new("maxMenuItem", true, maxMenuItem, _settings);
+ showMax.Changed += delegate { treeView.Columns[3].IsVisible = showMax.Value; };
+
+ var _ = new UserOption("startMinMenuItem", false, startMinMenuItem, _settings);
+ _minimizeToTray = new UserOption("minTrayMenuItem", true, minTrayMenuItem, _settings);
+ _minimizeToTray.Changed += delegate { _systemTray.IsMainIconEnabled = _minimizeToTray.Value; };
+
+ _minimizeOnClose = new UserOption("minCloseMenuItem", false, minCloseMenuItem, _settings);
+
+ _autoStart = new UserOption(null, _startupManager.Startup, startupMenuItem, _settings);
+ _autoStart.Changed += delegate
{
- get { return authWebServerMenuItem.Checked; }
- set { authWebServerMenuItem.Checked = value; }
- }
-
- public HttpServer Server { get; }
-
- private void BackgroundUpdater_DoWork(object sender, DoWorkEventArgs e)
- {
- _computer.Accept(_updateVisitor);
-
- if (_logSensors != null && _logSensors.Value && _delayCount >= 4)
- _logger.Log();
-
- if (_delayCount < 4)
- _delayCount++;
-
- _plotPanel.InvalidatePlot();
- }
-
- private void PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs eventArgs)
- {
- if (eventArgs.Mode == Microsoft.Win32.PowerModes.Resume)
- {
- _computer.Reset();
- }
- }
-
- private void InitializeSplitter()
- {
- splitContainer.SplitterDistance = _settings.GetValue("splitContainer.SplitterDistance", 400);
- splitContainer.SplitterMoved += delegate { _settings.SetValue("splitContainer.SplitterDistance", splitContainer.SplitterDistance); };
- }
-
- private void InitializePlotForm()
- {
- _plotForm = new Form { FormBorderStyle = FormBorderStyle.SizableToolWindow, ShowInTaskbar = false, StartPosition = FormStartPosition.Manual };
- AddOwnedForm(_plotForm);
- _plotForm.Bounds = new Rectangle
- {
- X = _settings.GetValue("plotForm.Location.X", -100000),
- Y = _settings.GetValue("plotForm.Location.Y", 100),
- Width = _settings.GetValue("plotForm.Width", 600),
- Height = _settings.GetValue("plotForm.Height", 400)
- };
-
- _showPlot = new UserOption("plotMenuItem", false, plotMenuItem, _settings);
- _plotLocation = new UserRadioGroup("plotLocation", 0, new[] { plotWindowMenuItem, plotBottomMenuItem, plotRightMenuItem }, _settings);
-
- _showPlot.Changed += delegate
- {
- if (_plotLocation.Value == 0)
- {
- if (_showPlot.Value && Visible)
- _plotForm.Show();
- else
- _plotForm.Hide();
- }
- else
- {
- splitContainer.Panel2Collapsed = !_showPlot.Value;
- }
-
- treeView.Invalidate();
- };
-
- _plotLocation.Changed += delegate
- {
- switch (_plotLocation.Value)
- {
- case 0:
- splitContainer.Panel2.Controls.Clear();
- splitContainer.Panel2Collapsed = true;
- _plotForm.Controls.Add(_plotPanel);
- if (_showPlot.Value && Visible)
- _plotForm.Show();
-
- break;
- case 1:
- _plotForm.Controls.Clear();
- _plotForm.Hide();
- splitContainer.Orientation = Orientation.Horizontal;
- splitContainer.Panel2.Controls.Add(_plotPanel);
- splitContainer.Panel2Collapsed = !_showPlot.Value;
- break;
- case 2:
- _plotForm.Controls.Clear();
- _plotForm.Hide();
- splitContainer.Orientation = Orientation.Vertical;
- splitContainer.Panel2.Controls.Add(_plotPanel);
- splitContainer.Panel2Collapsed = !_showPlot.Value;
- break;
- }
- };
-
- _plotForm.FormClosing += delegate(object sender, FormClosingEventArgs e)
- {
- if (e.CloseReason == CloseReason.UserClosing)
- {
- // just switch off the plotting when the user closes the form
- if (_plotLocation.Value == 0)
- {
- _showPlot.Value = false;
- }
-
- e.Cancel = true;
- }
- };
-
- void MoveOrResizePlotForm(object sender, EventArgs e)
- {
- if (_plotForm.WindowState != FormWindowState.Minimized)
- {
- _settings.SetValue("plotForm.Location.X", _plotForm.Bounds.X);
- _settings.SetValue("plotForm.Location.Y", _plotForm.Bounds.Y);
- _settings.SetValue("plotForm.Width", _plotForm.Bounds.Width);
- _settings.SetValue("plotForm.Height", _plotForm.Bounds.Height);
- }
- }
-
- _plotForm.Move += MoveOrResizePlotForm;
- _plotForm.Resize += MoveOrResizePlotForm;
-
- _plotForm.VisibleChanged += delegate
- {
- Rectangle bounds = new(_plotForm.Location, _plotForm.Size);
- Screen screen = Screen.FromRectangle(bounds);
- Rectangle intersection = Rectangle.Intersect(screen.WorkingArea, bounds);
- if (intersection.Width < Math.Min(16, bounds.Width) ||
- intersection.Height < Math.Min(16, bounds.Height))
- {
- _plotForm.Location = new Point(screen.WorkingArea.Width / 2 - bounds.Width / 2,
- screen.WorkingArea.Height / 2 - bounds.Height / 2);
- }
- };
-
- VisibleChanged += delegate
- {
- if (Visible && _showPlot.Value && _plotLocation.Value == 0)
- _plotForm.Show();
- else
- _plotForm.Hide();
- };
- }
-
- private void InsertSorted(IList nodes, HardwareNode node)
- {
- int i = 0;
- while (i < nodes.Count && nodes[i] is HardwareNode && ((HardwareNode)nodes[i]).Hardware.HardwareType <= node.Hardware.HardwareType)
- i++;
-
- nodes.Insert(i, node);
- }
-
- private void SubHardwareAdded(IHardware hardware, Node node)
- {
- HardwareNode hardwareNode = new(hardware, _settings, _unitManager);
- hardwareNode.PlotSelectionChanged += PlotSelectionChanged;
- InsertSorted(node.Nodes, hardwareNode);
- foreach (IHardware subHardware in hardware.SubHardware)
- SubHardwareAdded(subHardware, hardwareNode);
- }
-
- private void HardwareAdded(IHardware hardware)
- {
- SubHardwareAdded(hardware, _root);
- PlotSelectionChanged(this, null);
- }
-
- private void HardwareRemoved(IHardware hardware)
- {
- List nodesToRemove = new();
- foreach (Node node in _root.Nodes)
- {
- if (node is HardwareNode hardwareNode && hardwareNode.Hardware == hardware)
- nodesToRemove.Add(hardwareNode);
- }
-
- foreach (HardwareNode hardwareNode in nodesToRemove)
- {
- _root.Nodes.Remove(hardwareNode);
- hardwareNode.PlotSelectionChanged -= PlotSelectionChanged;
- }
-
- PlotSelectionChanged(this, null);
- }
-
- private void NodeTextBoxText_DrawText(object sender, DrawEventArgs e)
- {
- if (e.Node.Tag is Node node)
- {
- if (node.IsVisible)
- {
- if (plotMenuItem.Checked && node is SensorNode sensorNode && _sensorPlotColors.TryGetValue(sensorNode.Sensor, out Color color))
- e.TextColor = color;
- }
- else
- e.TextColor = Color.DarkGray;
- }
- }
-
- private void PlotSelectionChanged(object sender, EventArgs e)
- {
- List selected = new();
- IDictionary colors = new Dictionary();
- int colorIndex = 0;
-
- foreach (TreeNodeAdv node in treeView.AllNodes)
- {
- if (node.Tag is SensorNode sensorNode)
- {
- if (sensorNode.Plot)
- {
- if (!sensorNode.PenColor.HasValue)
- {
- colors.Add(sensorNode.Sensor,
- _plotColorPalette[colorIndex % _plotColorPalette.Length]);
- }
-
- selected.Add(sensorNode.Sensor);
- }
-
- colorIndex++;
- }
- }
-
- // if a sensor is assigned a color that's already being used by another
- // sensor, try to assign it a new color. This is done only after the
- // previous loop sets an unchanging default color for all sensors, so that
- // colors jump around as little as possible as sensors get added/removed
- // from the plot
- var usedColors = new List();
- foreach (ISensor curSelectedSensor in selected)
- {
- if (!colors.ContainsKey(curSelectedSensor))
- continue;
-
- Color curColor = colors[curSelectedSensor];
- if (usedColors.Contains(curColor))
- {
- foreach (Color potentialNewColor in _plotColorPalette)
- {
- if (!colors.Values.Contains(potentialNewColor))
- {
- colors[curSelectedSensor] = potentialNewColor;
- usedColors.Add(potentialNewColor);
- break;
- }
- }
- }
- else
- {
- usedColors.Add(curColor);
- }
- }
-
- foreach (TreeNodeAdv node in treeView.AllNodes)
- {
- if (node.Tag is SensorNode sensorNode && sensorNode.Plot && sensorNode.PenColor.HasValue)
- colors.Add(sensorNode.Sensor, sensorNode.PenColor.Value);
- }
-
- _sensorPlotColors = colors;
- _plotPanel.SetSensors(selected, colors);
- }
-
- private void NodeTextBoxText_EditorShowing(object sender, CancelEventArgs e)
- {
- e.Cancel = !(treeView.CurrentNode != null && (treeView.CurrentNode.Tag is SensorNode || treeView.CurrentNode.Tag is HardwareNode));
- }
-
- private void NodeCheckBox_IsVisibleValueNeeded(object sender, NodeControlValueEventArgs e)
- {
- e.Value = e.Node.Tag is SensorNode && plotMenuItem.Checked;
- }
-
- private void ExitClick(object sender, EventArgs e)
- {
- CloseApplication();
- }
-
- private void Timer_Tick(object sender, EventArgs e)
- {
- treeView.Invalidate();
- _systemTray.Redraw();
- _gadget?.Redraw();
- _wmiProvider?.Update();
-
- if (!backgroundUpdater.IsBusy)
- backgroundUpdater.RunWorkerAsync();
-
- RestoreCollapsedNodeState(treeView);
- }
-
- private void SaveConfiguration()
- {
- if (_plotPanel == null || _settings == null)
- return;
-
- _plotPanel.SetCurrentSettings();
-
- foreach (TreeColumn column in treeView.Columns)
- _settings.SetValue("treeView.Columns." + column.Header + ".Width", column.Width);
-
- _settings.SetValue("listenerPort", Server.ListenerPort);
- _settings.SetValue("authenticationEnabled", Server.AuthEnabled);
- _settings.SetValue("authenticationUserName", Server.UserName);
- _settings.SetValue("authenticationPassword", Server.Password);
-
- string fileName = Path.ChangeExtension(Application.ExecutablePath, ".config");
-
try
{
- _settings.Save(fileName);
+ _startupManager.Startup = _autoStart.Value;
}
- catch (UnauthorizedAccessException)
+ catch (InvalidOperationException)
{
- MessageBox.Show("Access to the path '" +
- fileName +
- "' is denied. " +
- "The current settings could not be saved.",
- "Error",
- MessageBoxButtons.OK,
- MessageBoxIcon.Error);
- }
- catch (IOException)
- {
- MessageBox.Show("The path '" +
- fileName +
- "' is not writeable. " +
- "The current settings could not be saved.",
+ MessageBox.Show("Updating the auto-startup option failed.",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
+
+ _autoStart.Value = _startupManager.Startup;
}
+ };
+
+ _readMainboardSensors = new UserOption("mainboardMenuItem", true, mainboardMenuItem, _settings);
+ _readMainboardSensors.Changed += delegate { _computer.IsMotherboardEnabled = _readMainboardSensors.Value; };
+
+ _readCpuSensors = new UserOption("cpuMenuItem", true, cpuMenuItem, _settings);
+ _readCpuSensors.Changed += delegate { _computer.IsCpuEnabled = _readCpuSensors.Value; };
+
+ _readRamSensors = new UserOption("ramMenuItem", true, ramMenuItem, _settings);
+ _readRamSensors.Changed += delegate { _computer.IsMemoryEnabled = _readRamSensors.Value; };
+
+ _readGpuSensors = new UserOption("gpuMenuItem", true, gpuMenuItem, _settings);
+ _readGpuSensors.Changed += delegate { _computer.IsGpuEnabled = _readGpuSensors.Value; };
+
+ _readFanControllersSensors = new UserOption("fanControllerMenuItem", true, fanControllerMenuItem, _settings);
+ _readFanControllersSensors.Changed += delegate { _computer.IsControllerEnabled = _readFanControllersSensors.Value; };
+
+ _readHddSensors = new UserOption("hddMenuItem", true, hddMenuItem, _settings);
+ _readHddSensors.Changed += delegate { _computer.IsStorageEnabled = _readHddSensors.Value; };
+
+ _readNicSensors = new UserOption("nicMenuItem", true, nicMenuItem, _settings);
+ _readNicSensors.Changed += delegate { _computer.IsNetworkEnabled = _readNicSensors.Value; };
+
+ _readPsuSensors = new UserOption("psuMenuItem", true, psuMenuItem, _settings);
+ _readPsuSensors.Changed += delegate { _computer.IsPsuEnabled = _readPsuSensors.Value; };
+
+ _readBatterySensors = new UserOption("batteryMenuItem", true, batteryMenuItem, _settings);
+ _readBatterySensors.Changed += delegate { _computer.IsBatteryEnabled = _readBatterySensors.Value; };
+
+ _showGadget = new UserOption("gadgetMenuItem", false, gadgetMenuItem, _settings);
+ _showGadget.Changed += delegate
+ {
+ if (_gadget != null)
+ _gadget.Visible = _showGadget.Value;
+ };
+
+ celsiusMenuItem.Checked = _unitManager.TemperatureUnit == TemperatureUnit.Celsius;
+ fahrenheitMenuItem.Checked = !celsiusMenuItem.Checked;
+
+ Server = new HttpServer(_root,
+ _settings.GetValue("listenerPort", 8085),
+ _settings.GetValue("authenticationEnabled", false),
+ _settings.GetValue("authenticationUserName", ""),
+ _settings.GetValue("authenticationPassword", ""));
+
+ if (Server.PlatformNotSupported)
+ {
+ webMenuItemSeparator.Visible = false;
+ webMenuItem.Visible = false;
}
- private void MainForm_Load(object sender, EventArgs e)
+ _runWebServer = new UserOption("runWebServerMenuItem", false, runWebServerMenuItem, _settings);
+ _runWebServer.Changed += delegate
{
- Rectangle newBounds = new()
+ if (_runWebServer.Value)
+ Server.StartHttpListener();
+ else
+ Server.StopHttpListener();
+ };
+
+ authWebServerMenuItem.Checked = _settings.GetValue("authenticationEnabled", false);
+
+ _logSensors = new UserOption("logSensorsMenuItem", false, logSensorsMenuItem, _settings);
+
+ _loggingInterval = new UserRadioGroup("loggingInterval",
+ 0,
+ new[]
+ {
+ log1sMenuItem,
+ log2sMenuItem,
+ log5sMenuItem,
+ log10sMenuItem,
+ log30sMenuItem,
+ log1minMenuItem,
+ log2minMenuItem,
+ log5minMenuItem,
+ log10minMenuItem,
+ log30minMenuItem,
+ log1hMenuItem,
+ log2hMenuItem,
+ log6hMenuItem
+ },
+ _settings);
+
+ _loggingInterval.Changed += (sender, e) =>
+ {
+ switch (_loggingInterval.Value)
{
- X = _settings.GetValue("mainForm.Location.X", Location.X),
- Y = _settings.GetValue("mainForm.Location.Y", Location.Y),
- Width = _settings.GetValue("mainForm.Width", 470),
- Height = _settings.GetValue("mainForm.Height", 640)
- };
+ case 0:
+ _logger.LoggingInterval = new TimeSpan(0, 0, 1);
+ break;
+ case 1:
+ _logger.LoggingInterval = new TimeSpan(0, 0, 2);
+ break;
+ case 2:
+ _logger.LoggingInterval = new TimeSpan(0, 0, 5);
+ break;
+ case 3:
+ _logger.LoggingInterval = new TimeSpan(0, 0, 10);
+ break;
+ case 4:
+ _logger.LoggingInterval = new TimeSpan(0, 0, 30);
+ break;
+ case 5:
+ _logger.LoggingInterval = new TimeSpan(0, 1, 0);
+ break;
+ case 6:
+ _logger.LoggingInterval = new TimeSpan(0, 2, 0);
+ break;
+ case 7:
+ _logger.LoggingInterval = new TimeSpan(0, 5, 0);
+ break;
+ case 8:
+ _logger.LoggingInterval = new TimeSpan(0, 10, 0);
+ break;
+ case 9:
+ _logger.LoggingInterval = new TimeSpan(0, 30, 0);
+ break;
+ case 10:
+ _logger.LoggingInterval = new TimeSpan(1, 0, 0);
+ break;
+ case 11:
+ _logger.LoggingInterval = new TimeSpan(2, 0, 0);
+ break;
+ case 12:
+ _logger.LoggingInterval = new TimeSpan(6, 0, 0);
+ break;
+ }
+ };
- Rectangle fullWorkingArea = new(int.MaxValue, int.MaxValue, int.MinValue, int.MinValue);
+ _sensorValuesTimeWindow = new UserRadioGroup("sensorValuesTimeWindow",
+ 10,
+ new[]
+ {
+ timeWindow30sMenuItem,
+ timeWindow1minMenuItem,
+ timeWindow2minMenuItem,
+ timeWindow5minMenuItem,
+ timeWindow10minMenuItem,
+ timeWindow30minMenuItem,
+ timeWindow1hMenuItem,
+ timeWindow2hMenuItem,
+ timeWindow6hMenuItem,
+ timeWindow12hMenuItem,
+ timeWindow24hMenuItem
+ },
+ _settings);
- foreach (Screen screen in Screen.AllScreens)
- fullWorkingArea = Rectangle.Union(fullWorkingArea, screen.Bounds);
-
- Rectangle intersection = Rectangle.Intersect(fullWorkingArea, newBounds);
- if (intersection.Width < 20 || intersection.Height < 20 || !_settings.Contains("mainForm.Location.X"))
+ _sensorValuesTimeWindow.Changed += (sender, e) =>
+ {
+ TimeSpan timeWindow = TimeSpan.Zero;
+ switch (_sensorValuesTimeWindow.Value)
{
- newBounds.X = (Screen.PrimaryScreen.WorkingArea.Width / 2) - (newBounds.Width / 2);
- newBounds.Y = (Screen.PrimaryScreen.WorkingArea.Height / 2) - (newBounds.Height / 2);
+ case 0:
+ timeWindow = new TimeSpan(0, 0, 30);
+ break;
+ case 1:
+ timeWindow = new TimeSpan(0, 1, 0);
+ break;
+ case 2:
+ timeWindow = new TimeSpan(0, 2, 0);
+ break;
+ case 3:
+ timeWindow = new TimeSpan(0, 5, 0);
+ break;
+ case 4:
+ timeWindow = new TimeSpan(0, 10, 0);
+ break;
+ case 5:
+ timeWindow = new TimeSpan(0, 30, 0);
+ break;
+ case 6:
+ timeWindow = new TimeSpan(1, 0, 0);
+ break;
+ case 7:
+ timeWindow = new TimeSpan(2, 0, 0);
+ break;
+ case 8:
+ timeWindow = new TimeSpan(6, 0, 0);
+ break;
+ case 9:
+ timeWindow = new TimeSpan(12, 0, 0);
+ break;
+ case 10:
+ timeWindow = new TimeSpan(24, 0, 0);
+ break;
}
- Bounds = newBounds;
+ _computer.Accept(new SensorVisitor(delegate(ISensor sensor) { sensor.ValuesTimeWindow = timeWindow; }));
+ };
- RestoreCollapsedNodeState(treeView);
+ InitializePlotForm();
+ InitializeSplitter();
- FormClosed += MainForm_FormClosed;
- }
+ startupMenuItem.Visible = _startupManager.IsAvailable;
- private void RestoreCollapsedNodeState(TreeViewAdv treeViewAdv)
+ if (startMinMenuItem.Checked)
{
- var collapsedHwNodes = treeViewAdv.AllNodes
- .Where(n => n.IsExpanded && n.Tag is IExpandPersistNode expandPersistNode && !expandPersistNode.Expanded)
- .OrderByDescending(n => n.Level)
- .ToList();
-
- foreach (TreeNodeAdv node in collapsedHwNodes)
+ if (!minTrayMenuItem.Checked)
{
- node.IsExpanded = false;
+ WindowState = FormWindowState.Minimized;
+ Show();
}
}
-
- private void CloseApplication()
+ else
{
- FormClosed -= MainForm_FormClosed;
+ Show();
+ }
- Visible = false;
- _systemTray.IsMainIconEnabled = false;
- timer.Enabled = false;
+ // Create a handle, otherwise calling Close() does not fire FormClosed
+
+ // Make sure the settings are saved when the user logs off
+ Microsoft.Win32.SystemEvents.SessionEnded += delegate
+ {
_computer.Close();
SaveConfiguration();
if (_runWebServer.Value)
Server.Quit();
+ };
- _systemTray.Dispose();
- timer.Dispose();
- backgroundUpdater.Dispose();
+ Microsoft.Win32.SystemEvents.PowerModeChanged += PowerModeChanged;
+ }
- Application.Exit();
- }
+ public bool AuthWebServerMenuItemChecked
+ {
+ get { return authWebServerMenuItem.Checked; }
+ set { authWebServerMenuItem.Checked = value; }
+ }
- private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
+ public HttpServer Server { get; }
+
+ private void BackgroundUpdater_DoWork(object sender, DoWorkEventArgs e)
+ {
+ _computer.Accept(_updateVisitor);
+
+ if (_logSensors != null && _logSensors.Value && _delayCount >= 4)
+ _logger.Log();
+
+ if (_delayCount < 4)
+ _delayCount++;
+
+ _plotPanel.InvalidatePlot();
+ }
+
+ private void PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs eventArgs)
+ {
+ if (eventArgs.Mode == Microsoft.Win32.PowerModes.Resume)
{
- CloseApplication();
+ _computer.Reset();
}
+ }
- private void AboutMenuItem_Click(object sender, EventArgs e)
+ private void InitializeSplitter()
+ {
+ splitContainer.SplitterDistance = _settings.GetValue("splitContainer.SplitterDistance", 400);
+ splitContainer.SplitterMoved += delegate { _settings.SetValue("splitContainer.SplitterDistance", splitContainer.SplitterDistance); };
+ }
+
+ private void InitializePlotForm()
+ {
+ _plotForm = new Form { FormBorderStyle = FormBorderStyle.SizableToolWindow, ShowInTaskbar = false, StartPosition = FormStartPosition.Manual };
+ AddOwnedForm(_plotForm);
+ _plotForm.Bounds = new Rectangle
{
- _ = new AboutBox().ShowDialog();
- }
+ X = _settings.GetValue("plotForm.Location.X", -100000),
+ Y = _settings.GetValue("plotForm.Location.Y", 100),
+ Width = _settings.GetValue("plotForm.Width", 600),
+ Height = _settings.GetValue("plotForm.Height", 400)
+ };
- private void TreeView_Click(object sender, EventArgs e)
+ _showPlot = new UserOption("plotMenuItem", false, plotMenuItem, _settings);
+ _plotLocation = new UserRadioGroup("plotLocation", 0, new[] { plotWindowMenuItem, plotBottomMenuItem, plotRightMenuItem }, _settings);
+
+ _showPlot.Changed += delegate
{
- if (!(e is MouseEventArgs m) || (m.Button != MouseButtons.Left && m.Button != MouseButtons.Right))
- return;
-
- NodeControlInfo info = treeView.GetNodeControlInfoAt(new Point(m.X, m.Y));
- if (m.Button == MouseButtons.Left && info.Node != null)
+ if (_plotLocation.Value == 0)
{
- if (info.Node.Tag is IExpandPersistNode expandPersistNode)
- {
- expandPersistNode.Expanded = info.Node.IsExpanded;
- }
-
- return;
- }
-
- treeView.SelectedNode = info.Node;
- if (info.Node != null)
- {
- if (info.Node.Tag is SensorNode node && node.Sensor != null)
- {
- treeContextMenu.Items.Clear();
- if (node.Sensor.Parameters.Count > 0)
- {
- ToolStripItem item = new ToolStripMenuItem("Parameters...");
- item.Click += delegate { ShowParameterForm(node.Sensor); };
- treeContextMenu.Items.Add(item);
- }
-
- if (nodeTextBoxText.EditEnabled)
- {
- ToolStripItem item = new ToolStripMenuItem("Rename");
- item.Click += delegate { nodeTextBoxText.BeginEdit(); };
- treeContextMenu.Items.Add(item);
- }
-
- if (node.IsVisible)
- {
- ToolStripItem item = new ToolStripMenuItem("Hide");
- item.Click += delegate { node.IsVisible = false; };
- treeContextMenu.Items.Add(item);
- }
- else
- {
- ToolStripItem item = new ToolStripMenuItem("Unhide");
- item.Click += delegate { node.IsVisible = true; };
- treeContextMenu.Items.Add(item);
- }
-
- treeContextMenu.Items.Add(new ToolStripSeparator());
- {
- ToolStripItem item = new ToolStripMenuItem("Pen Color...");
- item.Click += delegate
- {
- ColorDialog dialog = new() { Color = node.PenColor.GetValueOrDefault() };
- if (dialog.ShowDialog() == DialogResult.OK)
- node.PenColor = dialog.Color;
- };
-
- treeContextMenu.Items.Add(item);
- }
-
- {
- ToolStripItem item = new ToolStripMenuItem("Reset Pen Color");
- item.Click += delegate { node.PenColor = null; };
- treeContextMenu.Items.Add(item);
- }
-
- treeContextMenu.Items.Add(new ToolStripSeparator());
- {
- ToolStripMenuItem item = new("Show in Tray") { Checked = _systemTray.Contains(node.Sensor) };
- item.Click += delegate
- {
- if (item.Checked)
- _systemTray.Remove(node.Sensor);
- else
- _systemTray.Add(node.Sensor, true);
- };
-
- treeContextMenu.Items.Add(item);
- }
-
- if (_gadget != null)
- {
- ToolStripMenuItem item = new("Show in Gadget") { Checked = _gadget.Contains(node.Sensor) };
- item.Click += delegate
- {
- if (item.Checked)
- {
- _gadget.Remove(node.Sensor);
- }
- else
- {
- _gadget.Add(node.Sensor);
- }
- };
-
- treeContextMenu.Items.Add(item);
- }
-
- if (node.Sensor.Control != null)
- {
- treeContextMenu.Items.Add(new ToolStripSeparator());
- IControl control = node.Sensor.Control;
- ToolStripMenuItem controlItem = new("Control");
- ToolStripItem defaultItem = new ToolStripMenuItem("Default") { Checked = control.ControlMode == ControlMode.Default };
- controlItem.DropDownItems.Add(defaultItem);
- defaultItem.Click += delegate { control.SetDefault(); };
- ToolStripMenuItem manualItem = new("Manual");
- controlItem.DropDownItems.Add(manualItem);
- manualItem.Checked = control.ControlMode == ControlMode.Software;
- for (int i = 0; i <= 100; i += 5)
- {
- if (i <= control.MaxSoftwareValue &&
- i >= control.MinSoftwareValue)
- {
- ToolStripMenuItem item = new ToolStripRadioButtonMenuItem(i + " %");
- manualItem.DropDownItems.Add(item);
- item.Checked = control.ControlMode == ControlMode.Software && Math.Round(control.SoftwareValue) == i;
- int softwareValue = i;
- item.Click += delegate { control.SetSoftware(softwareValue); };
- }
- }
-
- treeContextMenu.Items.Add(controlItem);
- }
-
- treeContextMenu.Show(treeView, new Point(m.X, m.Y));
- }
-
- if (info.Node.Tag is HardwareNode hardwareNode && hardwareNode.Hardware != null)
- {
- treeContextMenu.Items.Clear();
-
- if (nodeTextBoxText.EditEnabled)
- {
- ToolStripItem item = new ToolStripMenuItem("Rename");
- item.Click += delegate { nodeTextBoxText.BeginEdit(); };
- treeContextMenu.Items.Add(item);
- }
-
- treeContextMenu.Show(treeView, new Point(m.X, m.Y));
- }
- }
- }
-
- private void SaveReportMenuItem_Click(object sender, EventArgs e)
- {
- string report = _computer.GetReport();
- if (saveFileDialog.ShowDialog() == DialogResult.OK)
- {
- using (TextWriter w = new StreamWriter(saveFileDialog.FileName))
- {
- w.Write(report);
- }
- }
- }
-
- private void SysTrayHideShow()
- {
- Visible = !Visible;
- if (Visible)
- Activate();
- }
-
- protected override void WndProc(ref Message m)
- {
- const int WM_SYSCOMMAND = 0x112;
- const int SC_MINIMIZE = 0xF020;
- const int SC_CLOSE = 0xF060;
-
- if (_minimizeToTray.Value && m.Msg == WM_SYSCOMMAND && m.WParam.ToInt64() == SC_MINIMIZE)
- {
- SysTrayHideShow();
- }
- else if (_minimizeOnClose.Value && m.Msg == WM_SYSCOMMAND && m.WParam.ToInt64() == SC_CLOSE)
- {
- //Apparently the user wants to minimize rather than close
- //Now we still need to check if we're going to the tray or not
- //Note: the correct way to do this would be to send out SC_MINIMIZE,
- //but since the code here is so simple,
- //that would just be a waste of time.
- if (_minimizeToTray.Value)
- SysTrayHideShow();
+ if (_showPlot.Value && Visible)
+ _plotForm.Show();
else
- WindowState = FormWindowState.Minimized;
+ _plotForm.Hide();
}
else
{
- base.WndProc(ref m);
+ splitContainer.Panel2Collapsed = !_showPlot.Value;
+ }
+
+ treeView.Invalidate();
+ };
+
+ _plotLocation.Changed += delegate
+ {
+ switch (_plotLocation.Value)
+ {
+ case 0:
+ splitContainer.Panel2.Controls.Clear();
+ splitContainer.Panel2Collapsed = true;
+ _plotForm.Controls.Add(_plotPanel);
+ if (_showPlot.Value && Visible)
+ _plotForm.Show();
+
+ break;
+ case 1:
+ _plotForm.Controls.Clear();
+ _plotForm.Hide();
+ splitContainer.Orientation = Orientation.Horizontal;
+ splitContainer.Panel2.Controls.Add(_plotPanel);
+ splitContainer.Panel2Collapsed = !_showPlot.Value;
+ break;
+ case 2:
+ _plotForm.Controls.Clear();
+ _plotForm.Hide();
+ splitContainer.Orientation = Orientation.Vertical;
+ splitContainer.Panel2.Controls.Add(_plotPanel);
+ splitContainer.Panel2Collapsed = !_showPlot.Value;
+ break;
+ }
+ };
+
+ _plotForm.FormClosing += delegate(object sender, FormClosingEventArgs e)
+ {
+ if (e.CloseReason == CloseReason.UserClosing)
+ {
+ // just switch off the plotting when the user closes the form
+ if (_plotLocation.Value == 0)
+ {
+ _showPlot.Value = false;
+ }
+
+ e.Cancel = true;
+ }
+ };
+
+ void MoveOrResizePlotForm(object sender, EventArgs e)
+ {
+ if (_plotForm.WindowState != FormWindowState.Minimized)
+ {
+ _settings.SetValue("plotForm.Location.X", _plotForm.Bounds.X);
+ _settings.SetValue("plotForm.Location.Y", _plotForm.Bounds.Y);
+ _settings.SetValue("plotForm.Width", _plotForm.Bounds.Width);
+ _settings.SetValue("plotForm.Height", _plotForm.Bounds.Height);
}
}
- private void HideShowClick(object sender, EventArgs e)
+ _plotForm.Move += MoveOrResizePlotForm;
+ _plotForm.Resize += MoveOrResizePlotForm;
+
+ _plotForm.VisibleChanged += delegate
+ {
+ Rectangle bounds = new(_plotForm.Location, _plotForm.Size);
+ Screen screen = Screen.FromRectangle(bounds);
+ Rectangle intersection = Rectangle.Intersect(screen.WorkingArea, bounds);
+ if (intersection.Width < Math.Min(16, bounds.Width) ||
+ intersection.Height < Math.Min(16, bounds.Height))
+ {
+ _plotForm.Location = new Point(screen.WorkingArea.Width / 2 - bounds.Width / 2,
+ screen.WorkingArea.Height / 2 - bounds.Height / 2);
+ }
+ };
+
+ VisibleChanged += delegate
+ {
+ if (Visible && _showPlot.Value && _plotLocation.Value == 0)
+ _plotForm.Show();
+ else
+ _plotForm.Hide();
+ };
+ }
+
+ private void InsertSorted(IList nodes, HardwareNode node)
+ {
+ int i = 0;
+ while (i < nodes.Count && nodes[i] is HardwareNode && ((HardwareNode)nodes[i]).Hardware.HardwareType <= node.Hardware.HardwareType)
+ i++;
+
+ nodes.Insert(i, node);
+ }
+
+ private void SubHardwareAdded(IHardware hardware, Node node)
+ {
+ HardwareNode hardwareNode = new(hardware, _settings, _unitManager);
+ hardwareNode.PlotSelectionChanged += PlotSelectionChanged;
+ InsertSorted(node.Nodes, hardwareNode);
+ foreach (IHardware subHardware in hardware.SubHardware)
+ SubHardwareAdded(subHardware, hardwareNode);
+ }
+
+ private void HardwareAdded(IHardware hardware)
+ {
+ SubHardwareAdded(hardware, _root);
+ PlotSelectionChanged(this, null);
+ }
+
+ private void HardwareRemoved(IHardware hardware)
+ {
+ List nodesToRemove = new();
+ foreach (Node node in _root.Nodes)
+ {
+ if (node is HardwareNode hardwareNode && hardwareNode.Hardware == hardware)
+ nodesToRemove.Add(hardwareNode);
+ }
+
+ foreach (HardwareNode hardwareNode in nodesToRemove)
+ {
+ _root.Nodes.Remove(hardwareNode);
+ hardwareNode.PlotSelectionChanged -= PlotSelectionChanged;
+ }
+
+ PlotSelectionChanged(this, null);
+ }
+
+ private void NodeTextBoxText_DrawText(object sender, DrawEventArgs e)
+ {
+ if (e.Node.Tag is Node node)
+ {
+ if (node.IsVisible)
+ {
+ if (plotMenuItem.Checked && node is SensorNode sensorNode && _sensorPlotColors.TryGetValue(sensorNode.Sensor, out Color color))
+ e.TextColor = color;
+ }
+ else
+ e.TextColor = Color.DarkGray;
+ }
+ }
+
+ private void PlotSelectionChanged(object sender, EventArgs e)
+ {
+ List selected = new();
+ IDictionary colors = new Dictionary();
+ int colorIndex = 0;
+
+ foreach (TreeNodeAdv node in treeView.AllNodes)
+ {
+ if (node.Tag is SensorNode sensorNode)
+ {
+ if (sensorNode.Plot)
+ {
+ if (!sensorNode.PenColor.HasValue)
+ {
+ colors.Add(sensorNode.Sensor,
+ _plotColorPalette[colorIndex % _plotColorPalette.Length]);
+ }
+
+ selected.Add(sensorNode.Sensor);
+ }
+
+ colorIndex++;
+ }
+ }
+
+ // if a sensor is assigned a color that's already being used by another
+ // sensor, try to assign it a new color. This is done only after the
+ // previous loop sets an unchanging default color for all sensors, so that
+ // colors jump around as little as possible as sensors get added/removed
+ // from the plot
+ var usedColors = new List();
+ foreach (ISensor curSelectedSensor in selected)
+ {
+ if (!colors.ContainsKey(curSelectedSensor))
+ continue;
+
+ Color curColor = colors[curSelectedSensor];
+ if (usedColors.Contains(curColor))
+ {
+ foreach (Color potentialNewColor in _plotColorPalette)
+ {
+ if (!colors.Values.Contains(potentialNewColor))
+ {
+ colors[curSelectedSensor] = potentialNewColor;
+ usedColors.Add(potentialNewColor);
+ break;
+ }
+ }
+ }
+ else
+ {
+ usedColors.Add(curColor);
+ }
+ }
+
+ foreach (TreeNodeAdv node in treeView.AllNodes)
+ {
+ if (node.Tag is SensorNode sensorNode && sensorNode.Plot && sensorNode.PenColor.HasValue)
+ colors.Add(sensorNode.Sensor, sensorNode.PenColor.Value);
+ }
+
+ _sensorPlotColors = colors;
+ _plotPanel.SetSensors(selected, colors);
+ }
+
+ private void NodeTextBoxText_EditorShowing(object sender, CancelEventArgs e)
+ {
+ e.Cancel = !(treeView.CurrentNode != null && (treeView.CurrentNode.Tag is SensorNode || treeView.CurrentNode.Tag is HardwareNode));
+ }
+
+ private void NodeCheckBox_IsVisibleValueNeeded(object sender, NodeControlValueEventArgs e)
+ {
+ e.Value = e.Node.Tag is SensorNode && plotMenuItem.Checked;
+ }
+
+ private void ExitClick(object sender, EventArgs e)
+ {
+ CloseApplication();
+ }
+
+ private void Timer_Tick(object sender, EventArgs e)
+ {
+ treeView.Invalidate();
+ _systemTray.Redraw();
+ _gadget?.Redraw();
+ _wmiProvider?.Update();
+
+ if (!backgroundUpdater.IsBusy)
+ backgroundUpdater.RunWorkerAsync();
+
+ RestoreCollapsedNodeState(treeView);
+ }
+
+ private void SaveConfiguration()
+ {
+ if (_plotPanel == null || _settings == null)
+ return;
+
+ _plotPanel.SetCurrentSettings();
+
+ foreach (TreeColumn column in treeView.Columns)
+ _settings.SetValue("treeView.Columns." + column.Header + ".Width", column.Width);
+
+ _settings.SetValue("listenerPort", Server.ListenerPort);
+ _settings.SetValue("authenticationEnabled", Server.AuthEnabled);
+ _settings.SetValue("authenticationUserName", Server.UserName);
+ _settings.SetValue("authenticationPassword", Server.Password);
+
+ string fileName = Path.ChangeExtension(Application.ExecutablePath, ".config");
+
+ try
+ {
+ _settings.Save(fileName);
+ }
+ catch (UnauthorizedAccessException)
+ {
+ MessageBox.Show("Access to the path '" +
+ fileName +
+ "' is denied. " +
+ "The current settings could not be saved.",
+ "Error",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Error);
+ }
+ catch (IOException)
+ {
+ MessageBox.Show("The path '" +
+ fileName +
+ "' is not writeable. " +
+ "The current settings could not be saved.",
+ "Error",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Error);
+ }
+ }
+
+ private void MainForm_Load(object sender, EventArgs e)
+ {
+ Rectangle newBounds = new()
+ {
+ X = _settings.GetValue("mainForm.Location.X", Location.X),
+ Y = _settings.GetValue("mainForm.Location.Y", Location.Y),
+ Width = _settings.GetValue("mainForm.Width", 470),
+ Height = _settings.GetValue("mainForm.Height", 640)
+ };
+
+ Rectangle fullWorkingArea = new(int.MaxValue, int.MaxValue, int.MinValue, int.MinValue);
+
+ foreach (Screen screen in Screen.AllScreens)
+ fullWorkingArea = Rectangle.Union(fullWorkingArea, screen.Bounds);
+
+ Rectangle intersection = Rectangle.Intersect(fullWorkingArea, newBounds);
+ if (intersection.Width < 20 || intersection.Height < 20 || !_settings.Contains("mainForm.Location.X"))
+ {
+ newBounds.X = (Screen.PrimaryScreen.WorkingArea.Width / 2) - (newBounds.Width / 2);
+ newBounds.Y = (Screen.PrimaryScreen.WorkingArea.Height / 2) - (newBounds.Height / 2);
+ }
+
+ Bounds = newBounds;
+
+ RestoreCollapsedNodeState(treeView);
+
+ FormClosed += MainForm_FormClosed;
+ }
+
+ private void RestoreCollapsedNodeState(TreeViewAdv treeViewAdv)
+ {
+ var collapsedHwNodes = treeViewAdv.AllNodes
+ .Where(n => n.IsExpanded && n.Tag is IExpandPersistNode expandPersistNode && !expandPersistNode.Expanded)
+ .OrderByDescending(n => n.Level)
+ .ToList();
+
+ foreach (TreeNodeAdv node in collapsedHwNodes)
+ {
+ node.IsExpanded = false;
+ }
+ }
+
+ private void CloseApplication()
+ {
+ FormClosed -= MainForm_FormClosed;
+
+ Visible = false;
+ _systemTray.IsMainIconEnabled = false;
+ timer.Enabled = false;
+ _computer.Close();
+ SaveConfiguration();
+ if (_runWebServer.Value)
+ Server.Quit();
+
+ _systemTray.Dispose();
+ timer.Dispose();
+ backgroundUpdater.Dispose();
+
+ Application.Exit();
+ }
+
+ private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
+ {
+ CloseApplication();
+ }
+
+ private void AboutMenuItem_Click(object sender, EventArgs e)
+ {
+ _ = new AboutBox().ShowDialog();
+ }
+
+ private void TreeView_Click(object sender, EventArgs e)
+ {
+ if (!(e is MouseEventArgs m) || (m.Button != MouseButtons.Left && m.Button != MouseButtons.Right))
+ return;
+
+ NodeControlInfo info = treeView.GetNodeControlInfoAt(new Point(m.X, m.Y));
+ if (m.Button == MouseButtons.Left && info.Node != null)
+ {
+ if (info.Node.Tag is IExpandPersistNode expandPersistNode)
+ {
+ expandPersistNode.Expanded = info.Node.IsExpanded;
+ }
+
+ return;
+ }
+
+ treeView.SelectedNode = info.Node;
+ if (info.Node != null)
+ {
+ if (info.Node.Tag is SensorNode node && node.Sensor != null)
+ {
+ treeContextMenu.Items.Clear();
+ if (node.Sensor.Parameters.Count > 0)
+ {
+ ToolStripItem item = new ToolStripMenuItem("Parameters...");
+ item.Click += delegate { ShowParameterForm(node.Sensor); };
+ treeContextMenu.Items.Add(item);
+ }
+
+ if (nodeTextBoxText.EditEnabled)
+ {
+ ToolStripItem item = new ToolStripMenuItem("Rename");
+ item.Click += delegate { nodeTextBoxText.BeginEdit(); };
+ treeContextMenu.Items.Add(item);
+ }
+
+ if (node.IsVisible)
+ {
+ ToolStripItem item = new ToolStripMenuItem("Hide");
+ item.Click += delegate { node.IsVisible = false; };
+ treeContextMenu.Items.Add(item);
+ }
+ else
+ {
+ ToolStripItem item = new ToolStripMenuItem("Unhide");
+ item.Click += delegate { node.IsVisible = true; };
+ treeContextMenu.Items.Add(item);
+ }
+
+ treeContextMenu.Items.Add(new ToolStripSeparator());
+ {
+ ToolStripItem item = new ToolStripMenuItem("Pen Color...");
+ item.Click += delegate
+ {
+ ColorDialog dialog = new() { Color = node.PenColor.GetValueOrDefault() };
+ if (dialog.ShowDialog() == DialogResult.OK)
+ node.PenColor = dialog.Color;
+ };
+
+ treeContextMenu.Items.Add(item);
+ }
+
+ {
+ ToolStripItem item = new ToolStripMenuItem("Reset Pen Color");
+ item.Click += delegate { node.PenColor = null; };
+ treeContextMenu.Items.Add(item);
+ }
+
+ treeContextMenu.Items.Add(new ToolStripSeparator());
+ {
+ ToolStripMenuItem item = new("Show in Tray") { Checked = _systemTray.Contains(node.Sensor) };
+ item.Click += delegate
+ {
+ if (item.Checked)
+ _systemTray.Remove(node.Sensor);
+ else
+ _systemTray.Add(node.Sensor, true);
+ };
+
+ treeContextMenu.Items.Add(item);
+ }
+
+ if (_gadget != null)
+ {
+ ToolStripMenuItem item = new("Show in Gadget") { Checked = _gadget.Contains(node.Sensor) };
+ item.Click += delegate
+ {
+ if (item.Checked)
+ {
+ _gadget.Remove(node.Sensor);
+ }
+ else
+ {
+ _gadget.Add(node.Sensor);
+ }
+ };
+
+ treeContextMenu.Items.Add(item);
+ }
+
+ if (node.Sensor.Control != null)
+ {
+ treeContextMenu.Items.Add(new ToolStripSeparator());
+ IControl control = node.Sensor.Control;
+ ToolStripMenuItem controlItem = new("Control");
+ ToolStripItem defaultItem = new ToolStripMenuItem("Default") { Checked = control.ControlMode == ControlMode.Default };
+ controlItem.DropDownItems.Add(defaultItem);
+ defaultItem.Click += delegate { control.SetDefault(); };
+ ToolStripMenuItem manualItem = new("Manual");
+ controlItem.DropDownItems.Add(manualItem);
+ manualItem.Checked = control.ControlMode == ControlMode.Software;
+ for (int i = 0; i <= 100; i += 5)
+ {
+ if (i <= control.MaxSoftwareValue &&
+ i >= control.MinSoftwareValue)
+ {
+ ToolStripMenuItem item = new ToolStripRadioButtonMenuItem(i + " %");
+ manualItem.DropDownItems.Add(item);
+ item.Checked = control.ControlMode == ControlMode.Software && Math.Round(control.SoftwareValue) == i;
+ int softwareValue = i;
+ item.Click += delegate { control.SetSoftware(softwareValue); };
+ }
+ }
+
+ treeContextMenu.Items.Add(controlItem);
+ }
+
+ treeContextMenu.Show(treeView, new Point(m.X, m.Y));
+ }
+
+ if (info.Node.Tag is HardwareNode hardwareNode && hardwareNode.Hardware != null)
+ {
+ treeContextMenu.Items.Clear();
+
+ if (nodeTextBoxText.EditEnabled)
+ {
+ ToolStripItem item = new ToolStripMenuItem("Rename");
+ item.Click += delegate { nodeTextBoxText.BeginEdit(); };
+ treeContextMenu.Items.Add(item);
+ }
+
+ treeContextMenu.Show(treeView, new Point(m.X, m.Y));
+ }
+ }
+ }
+
+ private void SaveReportMenuItem_Click(object sender, EventArgs e)
+ {
+ string report = _computer.GetReport();
+ if (saveFileDialog.ShowDialog() == DialogResult.OK)
+ {
+ using (TextWriter w = new StreamWriter(saveFileDialog.FileName))
+ {
+ w.Write(report);
+ }
+ }
+ }
+
+ private void SysTrayHideShow()
+ {
+ Visible = !Visible;
+ if (Visible)
+ Activate();
+ }
+
+ protected override void WndProc(ref Message m)
+ {
+ const int WM_SYSCOMMAND = 0x112;
+ const int SC_MINIMIZE = 0xF020;
+ const int SC_CLOSE = 0xF060;
+
+ if (_minimizeToTray.Value && m.Msg == WM_SYSCOMMAND && m.WParam.ToInt64() == SC_MINIMIZE)
{
SysTrayHideShow();
}
-
- private void ShowParameterForm(ISensor sensorForm)
+ else if (_minimizeOnClose.Value && m.Msg == WM_SYSCOMMAND && m.WParam.ToInt64() == SC_CLOSE)
{
- ParameterForm form = new() { Parameters = sensorForm.Parameters, captionLabel = { Text = sensorForm.Name } };
- form.ShowDialog();
+ //Apparently the user wants to minimize rather than close
+ //Now we still need to check if we're going to the tray or not
+ //Note: the correct way to do this would be to send out SC_MINIMIZE,
+ //but since the code here is so simple,
+ //that would just be a waste of time.
+ if (_minimizeToTray.Value)
+ SysTrayHideShow();
+ else
+ WindowState = FormWindowState.Minimized;
}
-
- private void TreeView_NodeMouseDoubleClick(object sender, TreeNodeAdvMouseEventArgs e)
+ else
{
- if (e.Node.Tag is SensorNode node && node.Sensor != null && node.Sensor.Parameters.Count > 0)
- ShowParameterForm(node.Sensor);
- }
-
- private void CelsiusMenuItem_Click(object sender, EventArgs e)
- {
- celsiusMenuItem.Checked = true;
- fahrenheitMenuItem.Checked = false;
- _unitManager.TemperatureUnit = TemperatureUnit.Celsius;
- }
-
- private void FahrenheitMenuItem_Click(object sender, EventArgs e)
- {
- celsiusMenuItem.Checked = false;
- fahrenheitMenuItem.Checked = true;
- _unitManager.TemperatureUnit = TemperatureUnit.Fahrenheit;
- }
-
- private void ResetMinMaxMenuItem_Click(object sender, EventArgs e)
- {
- _computer.Accept(new SensorVisitor(delegate(ISensor sensorClick)
- {
- sensorClick.ResetMin();
- sensorClick.ResetMax();
- }));
- }
-
- private void MainForm_MoveOrResize(object sender, EventArgs e)
- {
- if (WindowState != FormWindowState.Minimized)
- {
- _settings.SetValue("mainForm.Location.X", Bounds.X);
- _settings.SetValue("mainForm.Location.Y", Bounds.Y);
- _settings.SetValue("mainForm.Width", Bounds.Width);
- _settings.SetValue("mainForm.Height", Bounds.Height);
- }
- }
-
- private void ResetClick(object sender, EventArgs e)
- {
- // disable the fallback MainIcon during reset, otherwise icon visibility
- // might be lost
- _systemTray.IsMainIconEnabled = false;
- _computer.Reset();
- // restore the MainIcon setting
- _systemTray.IsMainIconEnabled = _minimizeToTray.Value;
- }
-
- private void TreeView_MouseMove(object sender, MouseEventArgs e)
- {
- _selectionDragging &= (e.Button & (MouseButtons.Left | MouseButtons.Right)) > 0;
- if (_selectionDragging)
- treeView.SelectedNode = treeView.GetNodeAt(e.Location);
- }
-
- private void TreeView_MouseDown(object sender, MouseEventArgs e)
- {
- _selectionDragging = true;
- }
-
- private void TreeView_MouseUp(object sender, MouseEventArgs e)
- {
- _selectionDragging = false;
- }
-
- private void ServerPortMenuItem_Click(object sender, EventArgs e)
- {
- new PortForm(this).ShowDialog();
- }
-
- private void AuthWebServerMenuItem_Click(object sender, EventArgs e)
- {
- new AuthForm(this).ShowDialog();
+ base.WndProc(ref m);
}
}
-}
+
+ private void HideShowClick(object sender, EventArgs e)
+ {
+ SysTrayHideShow();
+ }
+
+ private void ShowParameterForm(ISensor sensorForm)
+ {
+ ParameterForm form = new() { Parameters = sensorForm.Parameters, captionLabel = { Text = sensorForm.Name } };
+ form.ShowDialog();
+ }
+
+ private void TreeView_NodeMouseDoubleClick(object sender, TreeNodeAdvMouseEventArgs e)
+ {
+ if (e.Node.Tag is SensorNode node && node.Sensor != null && node.Sensor.Parameters.Count > 0)
+ ShowParameterForm(node.Sensor);
+ }
+
+ private void CelsiusMenuItem_Click(object sender, EventArgs e)
+ {
+ celsiusMenuItem.Checked = true;
+ fahrenheitMenuItem.Checked = false;
+ _unitManager.TemperatureUnit = TemperatureUnit.Celsius;
+ }
+
+ private void FahrenheitMenuItem_Click(object sender, EventArgs e)
+ {
+ celsiusMenuItem.Checked = false;
+ fahrenheitMenuItem.Checked = true;
+ _unitManager.TemperatureUnit = TemperatureUnit.Fahrenheit;
+ }
+
+ private void ResetMinMaxMenuItem_Click(object sender, EventArgs e)
+ {
+ _computer.Accept(new SensorVisitor(delegate(ISensor sensorClick)
+ {
+ sensorClick.ResetMin();
+ sensorClick.ResetMax();
+ }));
+ }
+
+ private void MainForm_MoveOrResize(object sender, EventArgs e)
+ {
+ if (WindowState != FormWindowState.Minimized)
+ {
+ _settings.SetValue("mainForm.Location.X", Bounds.X);
+ _settings.SetValue("mainForm.Location.Y", Bounds.Y);
+ _settings.SetValue("mainForm.Width", Bounds.Width);
+ _settings.SetValue("mainForm.Height", Bounds.Height);
+ }
+ }
+
+ private void ResetClick(object sender, EventArgs e)
+ {
+ // disable the fallback MainIcon during reset, otherwise icon visibility
+ // might be lost
+ _systemTray.IsMainIconEnabled = false;
+ _computer.Reset();
+ // restore the MainIcon setting
+ _systemTray.IsMainIconEnabled = _minimizeToTray.Value;
+ }
+
+ private void TreeView_MouseMove(object sender, MouseEventArgs e)
+ {
+ _selectionDragging &= (e.Button & (MouseButtons.Left | MouseButtons.Right)) > 0;
+ if (_selectionDragging)
+ treeView.SelectedNode = treeView.GetNodeAt(e.Location);
+ }
+
+ private void TreeView_MouseDown(object sender, MouseEventArgs e)
+ {
+ _selectionDragging = true;
+ }
+
+ private void TreeView_MouseUp(object sender, MouseEventArgs e)
+ {
+ _selectionDragging = false;
+ }
+
+ private void ServerPortMenuItem_Click(object sender, EventArgs e)
+ {
+ new PortForm(this).ShowDialog();
+ }
+
+ private void AuthWebServerMenuItem_Click(object sender, EventArgs e)
+ {
+ new AuthForm(this).ShowDialog();
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/Node.cs b/LibreHardwareMonitor/UI/Node.cs
index 1ef5131..875d720 100644
--- a/LibreHardwareMonitor/UI/Node.cs
+++ b/LibreHardwareMonitor/UI/Node.cs
@@ -8,162 +8,161 @@ using System;
using System.Collections.ObjectModel;
using System.Drawing;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class Node
{
- public class Node
+ private Node _parent;
+ private readonly NodeCollection _nodes;
+ private string _text;
+ private bool _visible;
+
+ public delegate void NodeEventHandler(Node node);
+ public event NodeEventHandler IsVisibleChanged;
+ public event NodeEventHandler NodeAdded;
+ public event NodeEventHandler NodeRemoved;
+
+ private TreeModel RootTreeModel()
{
- private Node _parent;
- private readonly NodeCollection _nodes;
- private string _text;
- private bool _visible;
-
- public delegate void NodeEventHandler(Node node);
- public event NodeEventHandler IsVisibleChanged;
- public event NodeEventHandler NodeAdded;
- public event NodeEventHandler NodeRemoved;
-
- private TreeModel RootTreeModel()
+ Node node = this;
+ while (node != null)
{
- Node node = this;
- while (node != null)
- {
- if (node.Model != null)
- return node.Model;
- node = node._parent;
- }
- return null;
+ if (node.Model != null)
+ return node.Model;
+ node = node._parent;
}
+ return null;
+ }
- public Node() : this(string.Empty) { }
+ public Node() : this(string.Empty) { }
- public Node(string text)
+ public Node(string text)
+ {
+ _text = text;
+ _nodes = new NodeCollection(this);
+ _visible = true;
+ }
+
+ public TreeModel Model { get; set; }
+
+ public Node Parent
+ {
+ get { return _parent; }
+ set
{
- _text = text;
- _nodes = new NodeCollection(this);
- _visible = true;
- }
-
- public TreeModel Model { get; set; }
-
- public Node Parent
- {
- get { return _parent; }
- set
+ if (value != _parent)
{
- if (value != _parent)
- {
- _parent?._nodes.Remove(this);
- value?._nodes.Add(this);
- }
- }
- }
-
- public Collection Nodes
- {
- get { return _nodes; }
- }
-
- public virtual string Text
- {
- get { return _text; }
- set
- {
- _text = value;
- }
- }
-
- public virtual string ToolTip { get; }
-
- public Image Image { get; set; }
-
- public virtual bool IsVisible
- {
- get { return _visible; }
- set
- {
- if (value != _visible)
- {
- _visible = value;
- TreeModel model = RootTreeModel();
- if (model != null && _parent != null)
- {
- int index = 0;
- for (int i = 0; i < _parent._nodes.Count; i++)
- {
- Node node = _parent._nodes[i];
- if (node == this)
- break;
- if (node.IsVisible || model.ForceVisible)
- index++;
- }
- if (model.ForceVisible)
- {
- model.OnNodeChanged(_parent, index, this);
- }
- else
- {
- if (value)
- model.OnNodeInserted(_parent, index, this);
- else
- model.OnNodeRemoved(_parent, index, this);
- }
- }
- IsVisibleChanged?.Invoke(this);
- }
- }
- }
-
- private class NodeCollection : Collection
- {
- private readonly Node _owner;
-
- public NodeCollection(Node owner)
- {
- _owner = owner;
- }
-
- protected override void ClearItems()
- {
- while (Count != 0)
- RemoveAt(Count - 1);
- }
-
- protected override void InsertItem(int index, Node item)
- {
- if (item == null)
- throw new ArgumentNullException(nameof(item));
-
- if (item._parent != _owner)
- {
- item._parent?._nodes.Remove(item);
- item._parent = _owner;
- base.InsertItem(index, item);
-
- TreeModel model = _owner.RootTreeModel();
- model?.OnStructureChanged(_owner);
- _owner.NodeAdded?.Invoke(item);
- }
- }
-
- protected override void RemoveItem(int index)
- {
- Node item = this[index];
- item._parent = null;
- base.RemoveItem(index);
-
- TreeModel model = _owner.RootTreeModel();
- model?.OnStructureChanged(_owner);
- _owner.NodeRemoved?.Invoke(item);
- }
-
- protected override void SetItem(int index, Node item)
- {
- if (item == null)
- throw new ArgumentNullException(nameof(item));
-
- RemoveAt(index);
- InsertItem(index, item);
+ _parent?._nodes.Remove(this);
+ value?._nodes.Add(this);
}
}
}
-}
+
+ public Collection Nodes
+ {
+ get { return _nodes; }
+ }
+
+ public virtual string Text
+ {
+ get { return _text; }
+ set
+ {
+ _text = value;
+ }
+ }
+
+ public virtual string ToolTip { get; }
+
+ public Image Image { get; set; }
+
+ public virtual bool IsVisible
+ {
+ get { return _visible; }
+ set
+ {
+ if (value != _visible)
+ {
+ _visible = value;
+ TreeModel model = RootTreeModel();
+ if (model != null && _parent != null)
+ {
+ int index = 0;
+ for (int i = 0; i < _parent._nodes.Count; i++)
+ {
+ Node node = _parent._nodes[i];
+ if (node == this)
+ break;
+ if (node.IsVisible || model.ForceVisible)
+ index++;
+ }
+ if (model.ForceVisible)
+ {
+ model.OnNodeChanged(_parent, index, this);
+ }
+ else
+ {
+ if (value)
+ model.OnNodeInserted(_parent, index, this);
+ else
+ model.OnNodeRemoved(_parent, index, this);
+ }
+ }
+ IsVisibleChanged?.Invoke(this);
+ }
+ }
+ }
+
+ private class NodeCollection : Collection
+ {
+ private readonly Node _owner;
+
+ public NodeCollection(Node owner)
+ {
+ _owner = owner;
+ }
+
+ protected override void ClearItems()
+ {
+ while (Count != 0)
+ RemoveAt(Count - 1);
+ }
+
+ protected override void InsertItem(int index, Node item)
+ {
+ if (item == null)
+ throw new ArgumentNullException(nameof(item));
+
+ if (item._parent != _owner)
+ {
+ item._parent?._nodes.Remove(item);
+ item._parent = _owner;
+ base.InsertItem(index, item);
+
+ TreeModel model = _owner.RootTreeModel();
+ model?.OnStructureChanged(_owner);
+ _owner.NodeAdded?.Invoke(item);
+ }
+ }
+
+ protected override void RemoveItem(int index)
+ {
+ Node item = this[index];
+ item._parent = null;
+ base.RemoveItem(index);
+
+ TreeModel model = _owner.RootTreeModel();
+ model?.OnStructureChanged(_owner);
+ _owner.NodeRemoved?.Invoke(item);
+ }
+
+ protected override void SetItem(int index, Node item)
+ {
+ if (item == null)
+ throw new ArgumentNullException(nameof(item));
+
+ RemoveAt(index);
+ InsertItem(index, item);
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/NodeToolTipProvider.cs b/LibreHardwareMonitor/UI/NodeToolTipProvider.cs
index 09ce236..1c19569 100644
--- a/LibreHardwareMonitor/UI/NodeToolTipProvider.cs
+++ b/LibreHardwareMonitor/UI/NodeToolTipProvider.cs
@@ -6,10 +6,9 @@
using Aga.Controls.Tree;
using Aga.Controls.Tree.NodeControls;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+internal class NodeToolTipProvider : IToolTipProvider
{
- internal class NodeToolTipProvider : IToolTipProvider
- {
- public string GetToolTip(TreeNodeAdv node, NodeControl nodeControl) => (node.Tag as Node)?.ToolTip;
- }
-}
+ public string GetToolTip(TreeNodeAdv node, NodeControl nodeControl) => (node.Tag as Node)?.ToolTip;
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/NotifyIconAdv.cs b/LibreHardwareMonitor/UI/NotifyIconAdv.cs
index f95b9e4..7798e45 100644
--- a/LibreHardwareMonitor/UI/NotifyIconAdv.cs
+++ b/LibreHardwareMonitor/UI/NotifyIconAdv.cs
@@ -11,295 +11,401 @@ using System.Runtime.InteropServices;
using System.Reflection;
using System.Windows.Forms;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class NotifyIconAdv : IDisposable
{
- public class NotifyIconAdv : IDisposable
+ private readonly NotifyIcon _genericNotifyIcon;
+ private readonly NotifyIconWindowsImplementation _windowsNotifyIcon;
+
+ public NotifyIconAdv()
{
- private readonly NotifyIcon _genericNotifyIcon;
- private readonly NotifyIconWindowsImplementation _windowsNotifyIcon;
+ if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix)
+ _genericNotifyIcon = new NotifyIcon();
+ else
+ _windowsNotifyIcon = new NotifyIconWindowsImplementation();
+ }
- public NotifyIconAdv()
+ public event EventHandler BalloonTipClicked
+ {
+ add
{
- if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix)
- _genericNotifyIcon = new NotifyIcon();
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.BalloonTipClicked += value;
else
- _windowsNotifyIcon = new NotifyIconWindowsImplementation();
+ _windowsNotifyIcon.BalloonTipClicked += value;
}
-
- public event EventHandler BalloonTipClicked
+ remove
{
- add
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.BalloonTipClicked += value;
- else
- _windowsNotifyIcon.BalloonTipClicked += value;
- }
- remove
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.BalloonTipClicked -= value;
- else
- _windowsNotifyIcon.BalloonTipClicked -= value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.BalloonTipClicked -= value;
+ else
+ _windowsNotifyIcon.BalloonTipClicked -= value;
}
+ }
- public event EventHandler BalloonTipClosed
+ public event EventHandler BalloonTipClosed
+ {
+ add
{
- add
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.BalloonTipClosed += value;
- else
- _windowsNotifyIcon.BalloonTipClosed += value;
- }
- remove
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.BalloonTipClosed -= value;
- else
- _windowsNotifyIcon.BalloonTipClosed -= value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.BalloonTipClosed += value;
+ else
+ _windowsNotifyIcon.BalloonTipClosed += value;
}
-
- public event EventHandler BalloonTipShown
+ remove
{
- add
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.BalloonTipShown += value;
- else
- _windowsNotifyIcon.BalloonTipShown += value;
- }
- remove
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.BalloonTipShown -= value;
- else
- _windowsNotifyIcon.BalloonTipShown -= value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.BalloonTipClosed -= value;
+ else
+ _windowsNotifyIcon.BalloonTipClosed -= value;
}
+ }
- public event EventHandler Click
+ public event EventHandler BalloonTipShown
+ {
+ add
{
- add
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.Click += value;
- else
- _windowsNotifyIcon.Click += value;
- }
- remove
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.Click -= value;
- else
- _windowsNotifyIcon.Click -= value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.BalloonTipShown += value;
+ else
+ _windowsNotifyIcon.BalloonTipShown += value;
}
-
- public event EventHandler DoubleClick
+ remove
{
- add
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.DoubleClick += value;
- else
- _windowsNotifyIcon.DoubleClick += value;
- }
- remove
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.DoubleClick -= value;
- else
- _windowsNotifyIcon.DoubleClick -= value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.BalloonTipShown -= value;
+ else
+ _windowsNotifyIcon.BalloonTipShown -= value;
}
+ }
- public event MouseEventHandler MouseClick
+ public event EventHandler Click
+ {
+ add
{
- add
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.MouseClick += value;
- else
- _windowsNotifyIcon.MouseClick += value;
- }
- remove
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.MouseClick -= value;
- else
- _windowsNotifyIcon.MouseClick -= value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.Click += value;
+ else
+ _windowsNotifyIcon.Click += value;
}
-
- public event MouseEventHandler MouseDoubleClick
+ remove
{
- add
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.MouseDoubleClick += value;
- else
- _windowsNotifyIcon.MouseDoubleClick += value;
- }
- remove
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.MouseDoubleClick -= value;
- else
- _windowsNotifyIcon.MouseDoubleClick -= value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.Click -= value;
+ else
+ _windowsNotifyIcon.Click -= value;
}
+ }
- public event MouseEventHandler MouseDown
+ public event EventHandler DoubleClick
+ {
+ add
{
- add
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.MouseDown += value;
- else
- _windowsNotifyIcon.MouseDown += value;
- }
- remove
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.MouseDown -= value;
- else
- _windowsNotifyIcon.MouseDown -= value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.DoubleClick += value;
+ else
+ _windowsNotifyIcon.DoubleClick += value;
}
-
- public event MouseEventHandler MouseMove
+ remove
{
- add
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.MouseMove += value;
- else
- _windowsNotifyIcon.MouseMove += value;
- }
- remove
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.MouseMove -= value;
- else
- _windowsNotifyIcon.MouseMove -= value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.DoubleClick -= value;
+ else
+ _windowsNotifyIcon.DoubleClick -= value;
}
+ }
- public event MouseEventHandler MouseUp
+ public event MouseEventHandler MouseClick
+ {
+ add
{
- add
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.MouseUp += value;
- else
- _windowsNotifyIcon.MouseUp += value;
- }
- remove
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.MouseUp -= value;
- else
- _windowsNotifyIcon.MouseUp -= value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.MouseClick += value;
+ else
+ _windowsNotifyIcon.MouseClick += value;
}
-
- public string BalloonTipText
+ remove
{
- get
- {
- if (_genericNotifyIcon != null)
- return _genericNotifyIcon.BalloonTipText;
-
-
- return _windowsNotifyIcon.BalloonTipText;
- }
- set
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.BalloonTipText = value;
- else
- _windowsNotifyIcon.BalloonTipText = value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.MouseClick -= value;
+ else
+ _windowsNotifyIcon.MouseClick -= value;
}
+ }
- public ToolTipIcon BalloonTipIcon
+ public event MouseEventHandler MouseDoubleClick
+ {
+ add
{
- get
- {
- if (_genericNotifyIcon != null)
- return _genericNotifyIcon.BalloonTipIcon;
-
-
- return _windowsNotifyIcon.BalloonTipIcon;
- }
- set
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.BalloonTipIcon = value;
- else
- _windowsNotifyIcon.BalloonTipIcon = value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.MouseDoubleClick += value;
+ else
+ _windowsNotifyIcon.MouseDoubleClick += value;
}
-
- public string BalloonTipTitle
+ remove
{
- get
- {
- if (_genericNotifyIcon != null)
- return _genericNotifyIcon.BalloonTipTitle;
-
-
- return _windowsNotifyIcon.BalloonTipTitle;
- }
- set
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.BalloonTipTitle = value;
- else
- _windowsNotifyIcon.BalloonTipTitle = value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.MouseDoubleClick -= value;
+ else
+ _windowsNotifyIcon.MouseDoubleClick -= value;
}
+ }
- public ContextMenuStrip ContextMenuStrip
+ public event MouseEventHandler MouseDown
+ {
+ add
{
- get
- {
- if (_genericNotifyIcon != null)
- return _genericNotifyIcon.ContextMenuStrip;
-
-
- return _windowsNotifyIcon.ContextMenuStrip;
- }
- set
- {
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.ContextMenuStrip = value;
- else
- _windowsNotifyIcon.ContextMenuStrip = value;
- }
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.MouseDown += value;
+ else
+ _windowsNotifyIcon.MouseDown += value;
}
+ remove
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.MouseDown -= value;
+ else
+ _windowsNotifyIcon.MouseDown -= value;
+ }
+ }
- public object Tag { get; set; }
+ public event MouseEventHandler MouseMove
+ {
+ add
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.MouseMove += value;
+ else
+ _windowsNotifyIcon.MouseMove += value;
+ }
+ remove
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.MouseMove -= value;
+ else
+ _windowsNotifyIcon.MouseMove -= value;
+ }
+ }
+
+ public event MouseEventHandler MouseUp
+ {
+ add
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.MouseUp += value;
+ else
+ _windowsNotifyIcon.MouseUp += value;
+ }
+ remove
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.MouseUp -= value;
+ else
+ _windowsNotifyIcon.MouseUp -= value;
+ }
+ }
+
+ public string BalloonTipText
+ {
+ get
+ {
+ if (_genericNotifyIcon != null)
+ return _genericNotifyIcon.BalloonTipText;
+
+
+ return _windowsNotifyIcon.BalloonTipText;
+ }
+ set
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.BalloonTipText = value;
+ else
+ _windowsNotifyIcon.BalloonTipText = value;
+ }
+ }
+
+ public ToolTipIcon BalloonTipIcon
+ {
+ get
+ {
+ if (_genericNotifyIcon != null)
+ return _genericNotifyIcon.BalloonTipIcon;
+
+
+ return _windowsNotifyIcon.BalloonTipIcon;
+ }
+ set
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.BalloonTipIcon = value;
+ else
+ _windowsNotifyIcon.BalloonTipIcon = value;
+ }
+ }
+
+ public string BalloonTipTitle
+ {
+ get
+ {
+ if (_genericNotifyIcon != null)
+ return _genericNotifyIcon.BalloonTipTitle;
+
+
+ return _windowsNotifyIcon.BalloonTipTitle;
+ }
+ set
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.BalloonTipTitle = value;
+ else
+ _windowsNotifyIcon.BalloonTipTitle = value;
+ }
+ }
+
+ public ContextMenuStrip ContextMenuStrip
+ {
+ get
+ {
+ if (_genericNotifyIcon != null)
+ return _genericNotifyIcon.ContextMenuStrip;
+
+
+ return _windowsNotifyIcon.ContextMenuStrip;
+ }
+ set
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.ContextMenuStrip = value;
+ else
+ _windowsNotifyIcon.ContextMenuStrip = value;
+ }
+ }
+
+ public object Tag { get; set; }
+
+ public Icon Icon
+ {
+ get
+ {
+ if (_genericNotifyIcon != null)
+ return _genericNotifyIcon.Icon;
+
+
+ return _windowsNotifyIcon.Icon;
+ }
+ set
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.Icon = value;
+ else
+ _windowsNotifyIcon.Icon = value;
+ }
+ }
+
+ public string Text
+ {
+ get
+ {
+ if (_genericNotifyIcon != null)
+ return _genericNotifyIcon.Text;
+
+
+ return _windowsNotifyIcon.Text;
+ }
+ set
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.Text = value;
+ else
+ _windowsNotifyIcon.Text = value;
+ }
+ }
+
+ public bool Visible
+ {
+ get
+ {
+ if (_genericNotifyIcon != null)
+ return _genericNotifyIcon.Visible;
+
+
+ return _windowsNotifyIcon.Visible;
+ }
+ set
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.Visible = value;
+ else
+ _windowsNotifyIcon.Visible = value;
+ }
+ }
+
+ public void Dispose()
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.Dispose();
+ else
+ _windowsNotifyIcon.Dispose();
+ }
+
+ public void ShowBalloonTip(int timeout)
+ {
+ ShowBalloonTip(timeout, BalloonTipTitle, BalloonTipText, BalloonTipIcon);
+ }
+
+ public void ShowBalloonTip(int timeout, string tipTitle, string tipText,
+ ToolTipIcon tipIcon)
+ {
+ if (_genericNotifyIcon != null)
+ _genericNotifyIcon.ShowBalloonTip(timeout, tipTitle, tipText, tipIcon);
+ else
+ _windowsNotifyIcon.ShowBalloonTip(timeout, tipTitle, tipText, tipIcon);
+ }
+
+ private class NotifyIconWindowsImplementation : Component
+ {
+
+ private static int _nextId;
+ private readonly object _syncObj = new object();
+ private Icon _icon;
+ private string _text = "";
+ private readonly int _id;
+ private bool _created;
+ private NotifyIconNativeWindow _window;
+ private bool _doubleClickDown;
+ private bool _visible;
+ private readonly MethodInfo _commandDispatch;
+
+ public event EventHandler BalloonTipClicked;
+ public event EventHandler BalloonTipClosed;
+ public event EventHandler BalloonTipShown;
+ public event EventHandler Click;
+ public event EventHandler DoubleClick;
+ public event MouseEventHandler MouseClick;
+ public event MouseEventHandler MouseDoubleClick;
+ public event MouseEventHandler MouseDown;
+ public event MouseEventHandler MouseMove;
+ public event MouseEventHandler MouseUp;
+
+ public string BalloonTipText { get; set; }
+ public ToolTipIcon BalloonTipIcon { get; set; }
+ public string BalloonTipTitle { get; set; }
+ public ContextMenuStrip ContextMenuStrip { get; set; }
public Icon Icon
{
get
{
- if (_genericNotifyIcon != null)
- return _genericNotifyIcon.Icon;
-
-
- return _windowsNotifyIcon.Icon;
+ return _icon;
}
set
{
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.Icon = value;
- else
- _windowsNotifyIcon.Icon = value;
+ if (_icon != value)
+ {
+ _icon = value;
+ UpdateNotifyIcon(_visible);
+ }
}
}
@@ -307,18 +413,22 @@ namespace LibreHardwareMonitor.UI
{
get
{
- if (_genericNotifyIcon != null)
- return _genericNotifyIcon.Text;
-
-
- return _windowsNotifyIcon.Text;
+ return _text;
}
set
{
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.Text = value;
- else
- _windowsNotifyIcon.Text = value;
+ if (value == null)
+ value = "";
+
+ if (value.Length > 63)
+ throw new ArgumentOutOfRangeException();
+
+ if (!value.Equals(_text))
+ {
+ _text = value;
+ if (_visible)
+ UpdateNotifyIcon(_visible);
+ }
}
}
@@ -326,27 +436,56 @@ namespace LibreHardwareMonitor.UI
{
get
{
- if (_genericNotifyIcon != null)
- return _genericNotifyIcon.Visible;
-
-
- return _windowsNotifyIcon.Visible;
+ return _visible;
}
set
{
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.Visible = value;
- else
- _windowsNotifyIcon.Visible = value;
+ if (_visible != value)
+ {
+ _visible = value;
+ UpdateNotifyIcon(_visible);
+ }
}
}
- public void Dispose()
+ public NotifyIconWindowsImplementation()
{
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.Dispose();
+ BalloonTipText = "";
+ BalloonTipTitle = "";
+
+ _commandDispatch = typeof(Form).Assembly.
+ GetType("System.Windows.Forms.Command").GetMethod("DispatchID",
+ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public,
+ null, new[] { typeof(int) }, null);
+
+ _id = ++_nextId;
+ _window = new NotifyIconNativeWindow(this);
+ UpdateNotifyIcon(_visible);
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ if (_window != null)
+ {
+ _icon = null;
+ _text = "";
+ UpdateNotifyIcon(false);
+ _window.DestroyHandle();
+ _window = null;
+ ContextMenuStrip = null;
+ }
+ }
else
- _windowsNotifyIcon.Dispose();
+ {
+ if (_window != null && _window.Handle != IntPtr.Zero)
+ {
+ NativeMethods.PostMessage(new HandleRef(_window, _window.Handle), WM_CLOSE, 0, 0);
+ _window.ReleaseHandle();
+ }
+ }
+ base.Dispose(disposing);
}
public void ShowBalloonTip(int timeout)
@@ -354,509 +493,369 @@ namespace LibreHardwareMonitor.UI
ShowBalloonTip(timeout, BalloonTipTitle, BalloonTipText, BalloonTipIcon);
}
- public void ShowBalloonTip(int timeout, string tipTitle, string tipText,
- ToolTipIcon tipIcon)
+ public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTipIcon tipIcon)
{
- if (_genericNotifyIcon != null)
- _genericNotifyIcon.ShowBalloonTip(timeout, tipTitle, tipText, tipIcon);
- else
- _windowsNotifyIcon.ShowBalloonTip(timeout, tipTitle, tipText, tipIcon);
+ if (timeout < 0)
+ throw new ArgumentOutOfRangeException(nameof(timeout));
+
+ if (string.IsNullOrEmpty(tipText))
+ throw new ArgumentException("tipText");
+
+ if (DesignMode)
+ return;
+
+ if (_created)
+ {
+ NativeMethods.NotifyIconData data = new NativeMethods.NotifyIconData();
+ if (_window.Handle == IntPtr.Zero)
+ _window.CreateHandle(new CreateParams());
+
+ data.Window = _window.Handle;
+ data.ID = _id;
+ data.Flags = NativeMethods.NotifyIconDataFlags.Info;
+ data.TimeoutOrVersion = timeout;
+ data.InfoTitle = tipTitle;
+ data.Info = tipText;
+ data.InfoFlags = (int)tipIcon;
+
+ NativeMethods.Shell_NotifyIcon(NativeMethods.NotifyIconMessage.Modify, data);
+ }
}
- private class NotifyIconWindowsImplementation : Component
+ private void ShowContextMenu()
{
+ if (ContextMenuStrip == null)
+ return;
- private static int _nextId;
- private readonly object _syncObj = new object();
- private Icon _icon;
- private string _text = "";
- private readonly int _id;
- private bool _created;
- private NotifyIconNativeWindow _window;
- private bool _doubleClickDown;
- private bool _visible;
- private readonly MethodInfo _commandDispatch;
+ NativeMethods.Point p = new NativeMethods.Point();
+ NativeMethods.GetCursorPos(ref p);
+ NativeMethods.SetForegroundWindow(new HandleRef(_window, _window.Handle));
- public event EventHandler BalloonTipClicked;
- public event EventHandler BalloonTipClosed;
- public event EventHandler BalloonTipShown;
- public event EventHandler Click;
- public event EventHandler DoubleClick;
- public event MouseEventHandler MouseClick;
- public event MouseEventHandler MouseDoubleClick;
- public event MouseEventHandler MouseDown;
- public event MouseEventHandler MouseMove;
- public event MouseEventHandler MouseUp;
+ ContextMenuStrip?.GetType().InvokeMember("ShowInTaskbar",
+ BindingFlags.NonPublic | BindingFlags.InvokeMethod |
+ BindingFlags.Instance, null, ContextMenuStrip, new object[] { p.X, p.Y });
+ }
- public string BalloonTipText { get; set; }
- public ToolTipIcon BalloonTipIcon { get; set; }
- public string BalloonTipTitle { get; set; }
- public ContextMenuStrip ContextMenuStrip { get; set; }
+ private void UpdateNotifyIcon(bool showNotifyIcon)
+ {
+ if (DesignMode)
+ return;
- public Icon Icon
+ lock (_syncObj)
{
- get
+ _window.LockReference(showNotifyIcon);
+
+ NativeMethods.NotifyIconData data = new NativeMethods.NotifyIconData { CallbackMessage = WM_TRAYMOUSEMESSAGE, Flags = NativeMethods.NotifyIconDataFlags.Message };
+
+ if (showNotifyIcon && _window.Handle == IntPtr.Zero)
+ _window.CreateHandle(new CreateParams());
+
+ data.Window = _window.Handle;
+ data.ID = _id;
+
+ if (_icon != null)
{
- return _icon;
+ data.Flags |= NativeMethods.NotifyIconDataFlags.Icon;
+ data.Icon = _icon.Handle;
}
- set
+
+ data.Flags |= NativeMethods.NotifyIconDataFlags.Tip;
+ data.Tip = _text;
+
+ if (showNotifyIcon && _icon != null)
{
- if (_icon != value)
+ if (!_created)
{
- _icon = value;
- UpdateNotifyIcon(_visible);
- }
- }
- }
-
- public string Text
- {
- get
- {
- return _text;
- }
- set
- {
- if (value == null)
- value = "";
-
- if (value.Length > 63)
- throw new ArgumentOutOfRangeException();
-
- if (!value.Equals(_text))
- {
- _text = value;
- if (_visible)
- UpdateNotifyIcon(_visible);
- }
- }
- }
-
- public bool Visible
- {
- get
- {
- return _visible;
- }
- set
- {
- if (_visible != value)
- {
- _visible = value;
- UpdateNotifyIcon(_visible);
- }
- }
- }
-
- public NotifyIconWindowsImplementation()
- {
- BalloonTipText = "";
- BalloonTipTitle = "";
-
- _commandDispatch = typeof(Form).Assembly.
- GetType("System.Windows.Forms.Command").GetMethod("DispatchID",
- BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public,
- null, new[] { typeof(int) }, null);
-
- _id = ++_nextId;
- _window = new NotifyIconNativeWindow(this);
- UpdateNotifyIcon(_visible);
- }
-
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- if (_window != null)
- {
- _icon = null;
- _text = "";
- UpdateNotifyIcon(false);
- _window.DestroyHandle();
- _window = null;
- ContextMenuStrip = null;
- }
- }
- else
- {
- if (_window != null && _window.Handle != IntPtr.Zero)
- {
- NativeMethods.PostMessage(new HandleRef(_window, _window.Handle), WM_CLOSE, 0, 0);
- _window.ReleaseHandle();
- }
- }
- base.Dispose(disposing);
- }
-
- public void ShowBalloonTip(int timeout)
- {
- ShowBalloonTip(timeout, BalloonTipTitle, BalloonTipText, BalloonTipIcon);
- }
-
- public void ShowBalloonTip(int timeout, string tipTitle, string tipText, ToolTipIcon tipIcon)
- {
- if (timeout < 0)
- throw new ArgumentOutOfRangeException(nameof(timeout));
-
- if (string.IsNullOrEmpty(tipText))
- throw new ArgumentException("tipText");
-
- if (DesignMode)
- return;
-
- if (_created)
- {
- NativeMethods.NotifyIconData data = new NativeMethods.NotifyIconData();
- if (_window.Handle == IntPtr.Zero)
- _window.CreateHandle(new CreateParams());
-
- data.Window = _window.Handle;
- data.ID = _id;
- data.Flags = NativeMethods.NotifyIconDataFlags.Info;
- data.TimeoutOrVersion = timeout;
- data.InfoTitle = tipTitle;
- data.Info = tipText;
- data.InfoFlags = (int)tipIcon;
-
- NativeMethods.Shell_NotifyIcon(NativeMethods.NotifyIconMessage.Modify, data);
- }
- }
-
- private void ShowContextMenu()
- {
- if (ContextMenuStrip == null)
- return;
-
- NativeMethods.Point p = new NativeMethods.Point();
- NativeMethods.GetCursorPos(ref p);
- NativeMethods.SetForegroundWindow(new HandleRef(_window, _window.Handle));
-
- ContextMenuStrip?.GetType().InvokeMember("ShowInTaskbar",
- BindingFlags.NonPublic | BindingFlags.InvokeMethod |
- BindingFlags.Instance, null, ContextMenuStrip, new object[] { p.X, p.Y });
- }
-
- private void UpdateNotifyIcon(bool showNotifyIcon)
- {
- if (DesignMode)
- return;
-
- lock (_syncObj)
- {
- _window.LockReference(showNotifyIcon);
-
- NativeMethods.NotifyIconData data = new NativeMethods.NotifyIconData { CallbackMessage = WM_TRAYMOUSEMESSAGE, Flags = NativeMethods.NotifyIconDataFlags.Message };
-
- if (showNotifyIcon && _window.Handle == IntPtr.Zero)
- _window.CreateHandle(new CreateParams());
-
- data.Window = _window.Handle;
- data.ID = _id;
-
- if (_icon != null)
- {
- data.Flags |= NativeMethods.NotifyIconDataFlags.Icon;
- data.Icon = _icon.Handle;
- }
-
- data.Flags |= NativeMethods.NotifyIconDataFlags.Tip;
- data.Tip = _text;
-
- if (showNotifyIcon && _icon != null)
- {
- if (!_created)
+ if (NativeMethods.Shell_NotifyIcon(NativeMethods.NotifyIconMessage.Modify, data))
{
- if (NativeMethods.Shell_NotifyIcon(NativeMethods.NotifyIconMessage.Modify, data))
- {
- _created = true;
- }
- else
- {
- int i = 0;
- do
- {
- _created = NativeMethods.Shell_NotifyIcon(NativeMethods.NotifyIconMessage.Add, data);
- if (!_created)
- {
- System.Threading.Thread.Sleep(200);
- i++;
- }
- } while (!_created && i < 40);
- }
+ _created = true;
}
else
- {
- NativeMethods.Shell_NotifyIcon(NativeMethods.NotifyIconMessage.Modify, data);
- }
- }
- else
- {
- if (_created)
{
int i = 0;
- bool deleted;
do
{
- deleted = NativeMethods.Shell_NotifyIcon(NativeMethods.NotifyIconMessage.Delete, data);
- if (!deleted)
+ _created = NativeMethods.Shell_NotifyIcon(NativeMethods.NotifyIconMessage.Add, data);
+ if (!_created)
{
System.Threading.Thread.Sleep(200);
i++;
}
- } while (!deleted && i < 40);
- _created = false;
- }
- }
- }
- }
-
- private void ProcessMouseDown(MouseButtons button, bool doubleClick)
- {
- if (doubleClick)
- {
- DoubleClick?.Invoke(this, new MouseEventArgs(button, 2, 0, 0, 0));
- MouseDoubleClick?.Invoke(this, new MouseEventArgs(button, 2, 0, 0, 0));
-
- _doubleClickDown = true;
- }
-
- MouseDown?.Invoke(this, new MouseEventArgs(button, doubleClick ? 2 : 1, 0, 0, 0));
- }
-
- private void ProcessMouseUp(MouseButtons button)
- {
- MouseUp?.Invoke(this, new MouseEventArgs(button, 0, 0, 0, 0));
-
- if (!_doubleClickDown)
- {
- Click?.Invoke(this, new MouseEventArgs(button, 0, 0, 0, 0));
- MouseClick?.Invoke(this, new MouseEventArgs(button, 0, 0, 0, 0));
- }
- _doubleClickDown = false;
- }
-
- private void ProcessInitMenuPopup(ref Message message)
- {
- _window.DefWndProc(ref message);
- }
-
- private void WndProc(ref Message message)
- {
- switch (message.Msg)
- {
- case WM_DESTROY:
- UpdateNotifyIcon(false);
- return;
- case WM_COMMAND:
- if (message.LParam != IntPtr.Zero)
- {
- _window.DefWndProc(ref message);
- return;
- }
- _commandDispatch.Invoke(null, new object[] { message.WParam.ToInt32() & 0xFFFF });
- return;
- case WM_INITMENUPOPUP:
- ProcessInitMenuPopup(ref message);
- return;
- case WM_TRAYMOUSEMESSAGE:
- switch ((int)message.LParam)
- {
- case WM_MOUSEMOVE:
- MouseMove?.Invoke(this,
- new MouseEventArgs(Control.MouseButtons, 0, 0, 0, 0));
- return;
- case WM_LBUTTONDOWN:
- ProcessMouseDown(MouseButtons.Left, false);
- return;
- case WM_LBUTTONUP:
- ProcessMouseUp(MouseButtons.Left);
- return;
- case WM_LBUTTONDBLCLK:
- ProcessMouseDown(MouseButtons.Left, true);
- return;
- case WM_RBUTTONDOWN:
- ProcessMouseDown(MouseButtons.Right, false);
- return;
- case WM_RBUTTONUP:
- if (ContextMenuStrip != null)
- ShowContextMenu();
- ProcessMouseUp(MouseButtons.Right);
- return;
- case WM_RBUTTONDBLCLK:
- ProcessMouseDown(MouseButtons.Right, true);
- return;
- case WM_MBUTTONDOWN:
- ProcessMouseDown(MouseButtons.Middle, false);
- return;
- case WM_MBUTTONUP:
- ProcessMouseUp(MouseButtons.Middle);
- return;
- case WM_MBUTTONDBLCLK:
- ProcessMouseDown(MouseButtons.Middle, true);
- return;
- case NIN_BALLOONSHOW:
- BalloonTipShown?.Invoke(this, EventArgs.Empty);
- return;
- case NIN_BALLOONHIDE:
- case NIN_BALLOONTIMEOUT:
- BalloonTipClosed?.Invoke(this, EventArgs.Empty);
- return;
- case NIN_BALLOONUSERCLICK:
- BalloonTipClicked?.Invoke(this, EventArgs.Empty);
- return;
- default:
- return;
- }
- }
-
- if (message.Msg == _wmTaskBarCreated)
- {
- lock (_syncObj)
- {
- _created = false;
- }
- UpdateNotifyIcon(_visible);
- }
-
- _window.DefWndProc(ref message);
- }
-
- private class NotifyIconNativeWindow : NativeWindow
- {
- private readonly NotifyIconWindowsImplementation _reference;
- private GCHandle _referenceHandle;
-
- internal NotifyIconNativeWindow(NotifyIconWindowsImplementation component)
- {
- _reference = component;
- }
-
- ~NotifyIconNativeWindow()
- {
- if (Handle != IntPtr.Zero)
- NativeMethods.PostMessage(new HandleRef(this, Handle), WM_CLOSE, 0, 0);
- }
-
- public void LockReference(bool locked)
- {
- if (locked)
- {
- if (!_referenceHandle.IsAllocated)
- {
- _referenceHandle = GCHandle.Alloc(_reference, GCHandleType.Normal);
+ } while (!_created && i < 40);
}
}
else
{
- if (_referenceHandle.IsAllocated)
- _referenceHandle.Free();
+ NativeMethods.Shell_NotifyIcon(NativeMethods.NotifyIconMessage.Modify, data);
}
}
-
- protected override void OnThreadException(Exception e)
+ else
{
- Application.OnThreadException(e);
+ if (_created)
+ {
+ int i = 0;
+ bool deleted;
+ do
+ {
+ deleted = NativeMethods.Shell_NotifyIcon(NativeMethods.NotifyIconMessage.Delete, data);
+ if (!deleted)
+ {
+ System.Threading.Thread.Sleep(200);
+ i++;
+ }
+ } while (!deleted && i < 40);
+ _created = false;
+ }
}
-
- protected override void WndProc(ref Message m)
- {
- _reference.WndProc(ref m);
- }
- }
-
- private const int WM_NULL = 0x00;
- private const int WM_DESTROY = 0x02;
- private const int WM_CLOSE = 0x10;
- private const int WM_COMMAND = 0x111;
- private const int WM_INITMENUPOPUP = 0x117;
- private const int WM_MOUSEMOVE = 0x200;
- private const int WM_LBUTTONDOWN = 0x201;
- private const int WM_LBUTTONUP = 0x202;
- private const int WM_LBUTTONDBLCLK = 0x203;
- private const int WM_RBUTTONDOWN = 0x204;
- private const int WM_RBUTTONUP = 0x205;
- private const int WM_RBUTTONDBLCLK = 0x206;
- private const int WM_MBUTTONDOWN = 0x207;
- private const int WM_MBUTTONUP = 0x208;
- private const int WM_MBUTTONDBLCLK = 0x209;
- private const int WM_TRAYMOUSEMESSAGE = 0x800;
-
- private const int NIN_BALLOONSHOW = 0x402;
- private const int NIN_BALLOONHIDE = 0x403;
- private const int NIN_BALLOONTIMEOUT = 0x404;
- private const int NIN_BALLOONUSERCLICK = 0x405;
-
- private static readonly int _wmTaskBarCreated = NativeMethods.RegisterWindowMessage("TaskbarCreated");
-
- private static class NativeMethods
- {
- private const string DllNameUser32 = "user32.dll";
- private const string DllNameShell32 = "shell32.dll";
-
- [DllImport(DllNameUser32, CharSet = CharSet.Auto)]
- public static extern IntPtr PostMessage(HandleRef hwnd, int msg, int wparam, int lparam);
-
- [DllImport(DllNameUser32, CharSet = CharSet.Auto)]
- public static extern int RegisterWindowMessage(string msg);
-
- [Flags]
- public enum NotifyIconDataFlags : int
- {
- Message = 0x1,
- Icon = 0x2,
- Tip = 0x4,
- State = 0x8,
- Info = 0x10
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
- public class NotifyIconData
- {
- private int _size = Marshal.SizeOf(typeof(NotifyIconData));
- public IntPtr Window;
- public int ID;
- public NotifyIconDataFlags Flags;
- public int CallbackMessage;
- public IntPtr Icon;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
- public string Tip;
- public int State;
- public int StateMask;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
- public string Info;
- public int TimeoutOrVersion;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
- public string InfoTitle;
- public int InfoFlags;
- }
-
- public enum NotifyIconMessage : int
- {
- Add = 0x0,
- Modify = 0x1,
- Delete = 0x2
- }
-
- [DllImport(DllNameShell32, CharSet = CharSet.Auto)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool Shell_NotifyIcon(NotifyIconMessage message, NotifyIconData pnid);
-
- [DllImport(DllNameUser32, CharSet = CharSet.Auto, ExactSpelling = true)]
- public static extern bool TrackPopupMenuEx(HandleRef hmenu, int fuFlags, int x, int y, HandleRef hwnd, IntPtr tpm);
-
- [StructLayout(LayoutKind.Sequential)]
- public struct Point
- {
- public readonly int X;
- public readonly int Y;
- }
-
- [DllImport(DllNameUser32, CharSet = CharSet.Auto, ExactSpelling = true)]
- public static extern bool GetCursorPos(ref Point point);
-
- [DllImport(DllNameUser32, CharSet = CharSet.Auto, ExactSpelling = true)]
- public static extern bool SetForegroundWindow(HandleRef hWnd);
}
}
+
+ private void ProcessMouseDown(MouseButtons button, bool doubleClick)
+ {
+ if (doubleClick)
+ {
+ DoubleClick?.Invoke(this, new MouseEventArgs(button, 2, 0, 0, 0));
+ MouseDoubleClick?.Invoke(this, new MouseEventArgs(button, 2, 0, 0, 0));
+
+ _doubleClickDown = true;
+ }
+
+ MouseDown?.Invoke(this, new MouseEventArgs(button, doubleClick ? 2 : 1, 0, 0, 0));
+ }
+
+ private void ProcessMouseUp(MouseButtons button)
+ {
+ MouseUp?.Invoke(this, new MouseEventArgs(button, 0, 0, 0, 0));
+
+ if (!_doubleClickDown)
+ {
+ Click?.Invoke(this, new MouseEventArgs(button, 0, 0, 0, 0));
+ MouseClick?.Invoke(this, new MouseEventArgs(button, 0, 0, 0, 0));
+ }
+ _doubleClickDown = false;
+ }
+
+ private void ProcessInitMenuPopup(ref Message message)
+ {
+ _window.DefWndProc(ref message);
+ }
+
+ private void WndProc(ref Message message)
+ {
+ switch (message.Msg)
+ {
+ case WM_DESTROY:
+ UpdateNotifyIcon(false);
+ return;
+ case WM_COMMAND:
+ if (message.LParam != IntPtr.Zero)
+ {
+ _window.DefWndProc(ref message);
+ return;
+ }
+ _commandDispatch.Invoke(null, new object[] { message.WParam.ToInt32() & 0xFFFF });
+ return;
+ case WM_INITMENUPOPUP:
+ ProcessInitMenuPopup(ref message);
+ return;
+ case WM_TRAYMOUSEMESSAGE:
+ switch ((int)message.LParam)
+ {
+ case WM_MOUSEMOVE:
+ MouseMove?.Invoke(this,
+ new MouseEventArgs(Control.MouseButtons, 0, 0, 0, 0));
+ return;
+ case WM_LBUTTONDOWN:
+ ProcessMouseDown(MouseButtons.Left, false);
+ return;
+ case WM_LBUTTONUP:
+ ProcessMouseUp(MouseButtons.Left);
+ return;
+ case WM_LBUTTONDBLCLK:
+ ProcessMouseDown(MouseButtons.Left, true);
+ return;
+ case WM_RBUTTONDOWN:
+ ProcessMouseDown(MouseButtons.Right, false);
+ return;
+ case WM_RBUTTONUP:
+ if (ContextMenuStrip != null)
+ ShowContextMenu();
+ ProcessMouseUp(MouseButtons.Right);
+ return;
+ case WM_RBUTTONDBLCLK:
+ ProcessMouseDown(MouseButtons.Right, true);
+ return;
+ case WM_MBUTTONDOWN:
+ ProcessMouseDown(MouseButtons.Middle, false);
+ return;
+ case WM_MBUTTONUP:
+ ProcessMouseUp(MouseButtons.Middle);
+ return;
+ case WM_MBUTTONDBLCLK:
+ ProcessMouseDown(MouseButtons.Middle, true);
+ return;
+ case NIN_BALLOONSHOW:
+ BalloonTipShown?.Invoke(this, EventArgs.Empty);
+ return;
+ case NIN_BALLOONHIDE:
+ case NIN_BALLOONTIMEOUT:
+ BalloonTipClosed?.Invoke(this, EventArgs.Empty);
+ return;
+ case NIN_BALLOONUSERCLICK:
+ BalloonTipClicked?.Invoke(this, EventArgs.Empty);
+ return;
+ default:
+ return;
+ }
+ }
+
+ if (message.Msg == _wmTaskBarCreated)
+ {
+ lock (_syncObj)
+ {
+ _created = false;
+ }
+ UpdateNotifyIcon(_visible);
+ }
+
+ _window.DefWndProc(ref message);
+ }
+
+ private class NotifyIconNativeWindow : NativeWindow
+ {
+ private readonly NotifyIconWindowsImplementation _reference;
+ private GCHandle _referenceHandle;
+
+ internal NotifyIconNativeWindow(NotifyIconWindowsImplementation component)
+ {
+ _reference = component;
+ }
+
+ ~NotifyIconNativeWindow()
+ {
+ if (Handle != IntPtr.Zero)
+ NativeMethods.PostMessage(new HandleRef(this, Handle), WM_CLOSE, 0, 0);
+ }
+
+ public void LockReference(bool locked)
+ {
+ if (locked)
+ {
+ if (!_referenceHandle.IsAllocated)
+ {
+ _referenceHandle = GCHandle.Alloc(_reference, GCHandleType.Normal);
+ }
+ }
+ else
+ {
+ if (_referenceHandle.IsAllocated)
+ _referenceHandle.Free();
+ }
+ }
+
+ protected override void OnThreadException(Exception e)
+ {
+ Application.OnThreadException(e);
+ }
+
+ protected override void WndProc(ref Message m)
+ {
+ _reference.WndProc(ref m);
+ }
+ }
+
+ private const int WM_NULL = 0x00;
+ private const int WM_DESTROY = 0x02;
+ private const int WM_CLOSE = 0x10;
+ private const int WM_COMMAND = 0x111;
+ private const int WM_INITMENUPOPUP = 0x117;
+ private const int WM_MOUSEMOVE = 0x200;
+ private const int WM_LBUTTONDOWN = 0x201;
+ private const int WM_LBUTTONUP = 0x202;
+ private const int WM_LBUTTONDBLCLK = 0x203;
+ private const int WM_RBUTTONDOWN = 0x204;
+ private const int WM_RBUTTONUP = 0x205;
+ private const int WM_RBUTTONDBLCLK = 0x206;
+ private const int WM_MBUTTONDOWN = 0x207;
+ private const int WM_MBUTTONUP = 0x208;
+ private const int WM_MBUTTONDBLCLK = 0x209;
+ private const int WM_TRAYMOUSEMESSAGE = 0x800;
+
+ private const int NIN_BALLOONSHOW = 0x402;
+ private const int NIN_BALLOONHIDE = 0x403;
+ private const int NIN_BALLOONTIMEOUT = 0x404;
+ private const int NIN_BALLOONUSERCLICK = 0x405;
+
+ private static readonly int _wmTaskBarCreated = NativeMethods.RegisterWindowMessage("TaskbarCreated");
+
+ private static class NativeMethods
+ {
+ private const string DllNameUser32 = "user32.dll";
+ private const string DllNameShell32 = "shell32.dll";
+
+ [DllImport(DllNameUser32, CharSet = CharSet.Auto)]
+ public static extern IntPtr PostMessage(HandleRef hwnd, int msg, int wparam, int lparam);
+
+ [DllImport(DllNameUser32, CharSet = CharSet.Auto)]
+ public static extern int RegisterWindowMessage(string msg);
+
+ [Flags]
+ public enum NotifyIconDataFlags : int
+ {
+ Message = 0x1,
+ Icon = 0x2,
+ Tip = 0x4,
+ State = 0x8,
+ Info = 0x10
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
+ public class NotifyIconData
+ {
+ private int _size = Marshal.SizeOf(typeof(NotifyIconData));
+ public IntPtr Window;
+ public int ID;
+ public NotifyIconDataFlags Flags;
+ public int CallbackMessage;
+ public IntPtr Icon;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
+ public string Tip;
+ public int State;
+ public int StateMask;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
+ public string Info;
+ public int TimeoutOrVersion;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
+ public string InfoTitle;
+ public int InfoFlags;
+ }
+
+ public enum NotifyIconMessage : int
+ {
+ Add = 0x0,
+ Modify = 0x1,
+ Delete = 0x2
+ }
+
+ [DllImport(DllNameShell32, CharSet = CharSet.Auto)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static extern bool Shell_NotifyIcon(NotifyIconMessage message, NotifyIconData pnid);
+
+ [DllImport(DllNameUser32, CharSet = CharSet.Auto, ExactSpelling = true)]
+ public static extern bool TrackPopupMenuEx(HandleRef hmenu, int fuFlags, int x, int y, HandleRef hwnd, IntPtr tpm);
+
+ [StructLayout(LayoutKind.Sequential)]
+ public struct Point
+ {
+ public readonly int X;
+ public readonly int Y;
+ }
+
+ [DllImport(DllNameUser32, CharSet = CharSet.Auto, ExactSpelling = true)]
+ public static extern bool GetCursorPos(ref Point point);
+
+ [DllImport(DllNameUser32, CharSet = CharSet.Auto, ExactSpelling = true)]
+ public static extern bool SetForegroundWindow(HandleRef hWnd);
+ }
}
-}
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/ParameterForm.cs b/LibreHardwareMonitor/UI/ParameterForm.cs
index 0a7c79b..ee8f867 100644
--- a/LibreHardwareMonitor/UI/ParameterForm.cs
+++ b/LibreHardwareMonitor/UI/ParameterForm.cs
@@ -10,127 +10,126 @@ using System.ComponentModel;
using System.Windows.Forms;
using LibreHardwareMonitor.Hardware;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public partial class ParameterForm : Form
{
- public partial class ParameterForm : Form
+ private IReadOnlyList _parameters;
+ private BindingList _parameterRows;
+
+ public ParameterForm()
{
- private IReadOnlyList _parameters;
- private BindingList _parameterRows;
+ InitializeComponent();
+ }
- public ParameterForm()
+ public IReadOnlyList Parameters
+ {
+ get
{
- InitializeComponent();
+ return _parameters;
}
-
- public IReadOnlyList Parameters
+ set
{
- get
+ _parameters = value;
+ _parameterRows = new BindingList();
+
+ foreach (IParameter parameter in _parameters)
{
- return _parameters;
- }
- set
- {
- _parameters = value;
- _parameterRows = new BindingList();
-
- foreach (IParameter parameter in _parameters)
- {
- _parameterRows.Add(new ParameterRow(parameter));
- }
-
- bindingSource.DataSource = _parameterRows;
- }
- }
-
- private class ParameterRow : INotifyPropertyChanged
- {
- public readonly IParameter Parameter;
- private float _value = float.NaN;
- private bool _default = true;
-
- public event PropertyChangedEventHandler PropertyChanged;
-
- private void NotifyPropertyChanged(String propertyName)
- {
- if (PropertyChanged != null)
- PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
+ _parameterRows.Add(new ParameterRow(parameter));
}
- public ParameterRow(IParameter parameter)
- {
- Parameter = parameter;
- Value = parameter.Value;
- Default = parameter.IsDefault;
- }
-
- public string Name
- {
- get { return Parameter.Name; }
- }
-
- public float Value
- {
- get { return _value; }
- set
- {
- _default = false;
- _value = value;
- NotifyPropertyChanged(nameof(Default));
- NotifyPropertyChanged(nameof(Value));
- }
- }
-
- public bool Default
- {
- get { return _default; }
- set
- {
- _default = value;
- if (_default)
- _value = Parameter.DefaultValue;
- NotifyPropertyChanged(nameof(Default));
- NotifyPropertyChanged(nameof(Value));
- }
- }
- }
-
- private void DataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
- {
- if (e.RowIndex >= 0 && e.RowIndex < _parameters.Count)
- descriptionLabel.Text = _parameters[e.RowIndex].Description;
- else
- descriptionLabel.Text = string.Empty;
- }
-
- private void DataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
- {
- if (e.ColumnIndex == 2 && !float.TryParse(e.FormattedValue.ToString(), out float _))
- {
- dataGridView.Rows[e.RowIndex].Cells[0].ErrorText = "Invalid value";
- e.Cancel = true;
- }
- }
-
- private void DataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
- {
- dataGridView.Rows[e.RowIndex].Cells[0].ErrorText = string.Empty;
- }
-
- private void OkButton_Click(object sender, EventArgs e)
- {
- foreach (ParameterRow row in _parameterRows)
- {
- if (row.Default)
- row.Parameter.IsDefault = true;
- else
- row.Parameter.Value = row.Value;
- }
- }
-
- private void DataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
- {
- if (dataGridView.CurrentCell is DataGridViewCheckBoxCell || dataGridView.CurrentCell is DataGridViewComboBoxCell)
- dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
+ bindingSource.DataSource = _parameterRows;
}
}
-}
+
+ private class ParameterRow : INotifyPropertyChanged
+ {
+ public readonly IParameter Parameter;
+ private float _value = float.NaN;
+ private bool _default = true;
+
+ public event PropertyChangedEventHandler PropertyChanged;
+
+ private void NotifyPropertyChanged(String propertyName)
+ {
+ if (PropertyChanged != null)
+ PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
+ }
+
+ public ParameterRow(IParameter parameter)
+ {
+ Parameter = parameter;
+ Value = parameter.Value;
+ Default = parameter.IsDefault;
+ }
+
+ public string Name
+ {
+ get { return Parameter.Name; }
+ }
+
+ public float Value
+ {
+ get { return _value; }
+ set
+ {
+ _default = false;
+ _value = value;
+ NotifyPropertyChanged(nameof(Default));
+ NotifyPropertyChanged(nameof(Value));
+ }
+ }
+
+ public bool Default
+ {
+ get { return _default; }
+ set
+ {
+ _default = value;
+ if (_default)
+ _value = Parameter.DefaultValue;
+ NotifyPropertyChanged(nameof(Default));
+ NotifyPropertyChanged(nameof(Value));
+ }
+ }
+ }
+
+ private void DataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
+ {
+ if (e.RowIndex >= 0 && e.RowIndex < _parameters.Count)
+ descriptionLabel.Text = _parameters[e.RowIndex].Description;
+ else
+ descriptionLabel.Text = string.Empty;
+ }
+
+ private void DataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
+ {
+ if (e.ColumnIndex == 2 && !float.TryParse(e.FormattedValue.ToString(), out float _))
+ {
+ dataGridView.Rows[e.RowIndex].Cells[0].ErrorText = "Invalid value";
+ e.Cancel = true;
+ }
+ }
+
+ private void DataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
+ {
+ dataGridView.Rows[e.RowIndex].Cells[0].ErrorText = string.Empty;
+ }
+
+ private void OkButton_Click(object sender, EventArgs e)
+ {
+ foreach (ParameterRow row in _parameterRows)
+ {
+ if (row.Default)
+ row.Parameter.IsDefault = true;
+ else
+ row.Parameter.Value = row.Value;
+ }
+ }
+
+ private void DataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
+ {
+ if (dataGridView.CurrentCell is DataGridViewCheckBoxCell || dataGridView.CurrentCell is DataGridViewComboBoxCell)
+ dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/PlotPanel.cs b/LibreHardwareMonitor/UI/PlotPanel.cs
index 5f35386..a509df4 100644
--- a/LibreHardwareMonitor/UI/PlotPanel.cs
+++ b/LibreHardwareMonitor/UI/PlotPanel.cs
@@ -17,403 +17,402 @@ using OxyPlot.Axes;
using OxyPlot.WindowsForms;
using OxyPlot.Series;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class PlotPanel : UserControl
{
- public class PlotPanel : UserControl
+ private readonly PersistentSettings _settings;
+ private readonly UnitManager _unitManager;
+ private readonly PlotView _plot;
+ private readonly PlotModel _model;
+ private readonly TimeSpanAxis _timeAxis = new TimeSpanAxis();
+ private readonly SortedDictionary _axes = new SortedDictionary();
+ private readonly Dictionary _annotations = new Dictionary();
+ private UserOption _stackedAxes;
+ private UserOption _showAxesLabels;
+ private UserOption _timeAxisEnableZoom;
+ private UserOption _yAxesEnableZoom;
+ private DateTime _now;
+ private float _dpiX;
+ private float _dpiY;
+ private double _dpiXScale = 1;
+ private double _dpiYScale = 1;
+ private Point _rightClickEnter;
+ private bool _cancelContextMenu = false;
+
+ public PlotPanel(PersistentSettings settings, UnitManager unitManager)
{
- private readonly PersistentSettings _settings;
- private readonly UnitManager _unitManager;
- private readonly PlotView _plot;
- private readonly PlotModel _model;
- private readonly TimeSpanAxis _timeAxis = new TimeSpanAxis();
- private readonly SortedDictionary _axes = new SortedDictionary();
- private readonly Dictionary _annotations = new Dictionary();
- private UserOption _stackedAxes;
- private UserOption _showAxesLabels;
- private UserOption _timeAxisEnableZoom;
- private UserOption _yAxesEnableZoom;
- private DateTime _now;
- private float _dpiX;
- private float _dpiY;
- private double _dpiXScale = 1;
- private double _dpiYScale = 1;
- private Point _rightClickEnter;
- private bool _cancelContextMenu = false;
+ _settings = settings;
+ _unitManager = unitManager;
- public PlotPanel(PersistentSettings settings, UnitManager unitManager)
+ SetDpi();
+ _model = CreatePlotModel();
+
+ _plot = new PlotView { Dock = DockStyle.Fill, Model = _model, BackColor = Color.White, ContextMenuStrip = CreateMenu() };
+ _plot.MouseDown += (sender, e) =>
{
- _settings = settings;
- _unitManager = unitManager;
-
- SetDpi();
- _model = CreatePlotModel();
-
- _plot = new PlotView { Dock = DockStyle.Fill, Model = _model, BackColor = Color.White, ContextMenuStrip = CreateMenu() };
- _plot.MouseDown += (sender, e) =>
+ if (e.Button == MouseButtons.Right)
{
- if (e.Button == MouseButtons.Right)
- {
- _rightClickEnter = e.Location;
- }
- };
- _plot.MouseMove += (sender, e) =>
+ _rightClickEnter = e.Location;
+ }
+ };
+ _plot.MouseMove += (sender, e) =>
+ {
+ if (e.Button == MouseButtons.Right)
{
- if (e.Button == MouseButtons.Right)
+ if (!_cancelContextMenu && e.Location.DistanceTo(_rightClickEnter) > 10.0f)
{
- if (!_cancelContextMenu && e.Location.DistanceTo(_rightClickEnter) > 10.0f)
- {
- _cancelContextMenu = true;
- }
+ _cancelContextMenu = true;
}
- };
+ }
+ };
+ UpdateAxesPosition();
+
+ SuspendLayout();
+ Controls.Add(_plot);
+ ResumeLayout(true);
+ }
+
+ public void SetCurrentSettings()
+ {
+ foreach (LinearAxis axis in _axes.Values)
+ {
+ _settings.SetValue("plotPanel.Min" + axis.Key, (float)axis.ActualMinimum);
+ _settings.SetValue("plotPanel.Max" + axis.Key, (float)axis.ActualMaximum);
+ }
+ _settings.SetValue("plotPanel.MinTimeSpan", (float)_timeAxis.ActualMinimum);
+ _settings.SetValue("plotPanel.MaxTimeSpan", (float)_timeAxis.ActualMaximum);
+ }
+
+ private ContextMenuStrip CreateMenu()
+ {
+ ContextMenuStrip menu = new ContextMenuStrip();
+ menu.Opening += (sender, e) =>
+ {
+ if (_cancelContextMenu)
+ {
+ e.Cancel = true;
+ _cancelContextMenu = false;
+ }
+ };
+
+ ToolStripMenuItem stackedAxesMenuItem = new ToolStripMenuItem("Stacked Axes");
+ _stackedAxes = new UserOption("stackedAxes", true, stackedAxesMenuItem, _settings);
+ _stackedAxes.Changed += (sender, e) =>
+ {
UpdateAxesPosition();
+ InvalidatePlot();
+ };
+ menu.Items.Add(stackedAxesMenuItem);
- SuspendLayout();
- Controls.Add(_plot);
- ResumeLayout(true);
- }
+ ToolStripMenuItem showAxesLabelsMenuItem = new ToolStripMenuItem("Show Axes Labels");
+ _showAxesLabels = new UserOption("showAxesLabels", true, showAxesLabelsMenuItem, _settings);
+ _showAxesLabels.Changed += (sender, e) =>
+ {
+ if (_showAxesLabels.Value)
+ _model.PlotMargins = new OxyThickness(double.NaN);
+ else
+ _model.PlotMargins = new OxyThickness(0);
+ };
+ menu.Items.Add(showAxesLabelsMenuItem);
- public void SetCurrentSettings()
+ ToolStripMenuItem timeAxisMenuItem = new ToolStripMenuItem("Time Axis");
+ ToolStripMenuItem[] timeAxisMenuItems =
+ { new ToolStripMenuItem("Enable Zoom"),
+ new ToolStripMenuItem("Auto", null, (s, e) => { TimeAxisZoom(0, double.NaN); }),
+ new ToolStripMenuItem("5 min", null, (s, e) => { TimeAxisZoom(0, 5 * 60); }),
+ new ToolStripMenuItem("10 min", null, (s, e) => { TimeAxisZoom(0, 10 * 60); }),
+ new ToolStripMenuItem("20 min", null, (s, e) => { TimeAxisZoom(0, 20 * 60); }),
+ new ToolStripMenuItem("30 min", null, (s, e) => { TimeAxisZoom(0, 30 * 60); }),
+ new ToolStripMenuItem("45 min", null, (s, e) => { TimeAxisZoom(0, 45 * 60); }),
+ new ToolStripMenuItem("1 h", null, (s, e) => { TimeAxisZoom(0, 60 * 60); }),
+ new ToolStripMenuItem("1.5 h", null, (s, e) => { TimeAxisZoom(0, 1.5 * 60 * 60); }),
+ new ToolStripMenuItem("2 h", null, (s, e) => { TimeAxisZoom(0, 2 * 60 * 60); }),
+ new ToolStripMenuItem("3 h", null, (s, e) => { TimeAxisZoom(0, 3 * 60 * 60); }),
+ new ToolStripMenuItem("6 h", null, (s, e) => { TimeAxisZoom(0, 6 * 60 * 60); }),
+ new ToolStripMenuItem("12 h", null, (s, e) => { TimeAxisZoom(0, 12 * 60 * 60); }),
+ new ToolStripMenuItem("24 h", null, (s, e) => { TimeAxisZoom(0, 24 * 60 * 60); }) };
+
+ foreach (ToolStripItem mi in timeAxisMenuItems)
+ timeAxisMenuItem.DropDownItems.Add(mi);
+ menu.Items.Add(timeAxisMenuItem);
+
+ _timeAxisEnableZoom = new UserOption("timeAxisEnableZoom", true, timeAxisMenuItems[0], _settings);
+ _timeAxisEnableZoom.Changed += (sender, e) =>
+ {
+ _timeAxis.IsZoomEnabled = _timeAxisEnableZoom.Value;
+ };
+
+ ToolStripMenuItem yAxesMenuItem = new ToolStripMenuItem("Value Axes");
+ ToolStripMenuItem[] yAxesMenuItems =
+ { new ToolStripMenuItem("Enable Zoom"),
+ new ToolStripMenuItem("Autoscale All", null, (s, e) => { AutoscaleAllYAxes(); }) };
+
+ foreach (ToolStripItem mi in yAxesMenuItems)
+ yAxesMenuItem.DropDownItems.Add(mi);
+ menu.Items.Add(yAxesMenuItem);
+
+ _yAxesEnableZoom = new UserOption("yAxesEnableZoom", true, yAxesMenuItems[0], _settings);
+ _yAxesEnableZoom.Changed += (sender, e) =>
{
foreach (LinearAxis axis in _axes.Values)
+ axis.IsZoomEnabled = _yAxesEnableZoom.Value;
+ };
+
+ return menu;
+ }
+
+ private PlotModel CreatePlotModel()
+ {
+ _timeAxis.Position = AxisPosition.Bottom;
+ _timeAxis.MajorGridlineStyle = LineStyle.Solid;
+ _timeAxis.MajorGridlineThickness = 1;
+ _timeAxis.MajorGridlineColor = OxyColor.FromRgb(192, 192, 192);
+ _timeAxis.MinorGridlineStyle = LineStyle.Solid;
+ _timeAxis.MinorGridlineThickness = 1;
+ _timeAxis.MinorGridlineColor = OxyColor.FromRgb(232, 232, 232);
+ _timeAxis.StartPosition = 1;
+ _timeAxis.EndPosition = 0;
+ _timeAxis.MinimumPadding = 0;
+ _timeAxis.MaximumPadding = 0;
+ _timeAxis.AbsoluteMinimum = 0;
+ _timeAxis.Minimum = 0;
+ _timeAxis.AbsoluteMaximum = 24 * 60 * 60;
+ _timeAxis.Zoom(
+ _settings.GetValue("plotPanel.MinTimeSpan", 0.0f),
+ _settings.GetValue("plotPanel.MaxTimeSpan", 10.0f * 60));
+ _timeAxis.StringFormat = "h:mm";
+
+ var units = new Dictionary
+ {
+ { SensorType.Voltage, "V" },
+ { SensorType.Current, "A" },
+ { SensorType.Clock, "MHz" },
+ { SensorType.Temperature, "°C" },
+ { SensorType.Load, "%" },
+ { SensorType.Fan, "RPM" },
+ { SensorType.Flow, "L/h" },
+ { SensorType.Control, "%" },
+ { SensorType.Level, "%" },
+ { SensorType.Factor, "1" },
+ { SensorType.Power, "W" },
+ { SensorType.Data, "GB" },
+ { SensorType.Frequency, "Hz" },
+ { SensorType.Energy, "mWh" },
+ { SensorType.Noise, "dBA" }
+ };
+
+ foreach (SensorType type in Enum.GetValues(typeof(SensorType)))
+ {
+ string typeName = type.ToString();
+ var axis = new LinearAxis
{
- _settings.SetValue("plotPanel.Min" + axis.Key, (float)axis.ActualMinimum);
- _settings.SetValue("plotPanel.Max" + axis.Key, (float)axis.ActualMaximum);
- }
- _settings.SetValue("plotPanel.MinTimeSpan", (float)_timeAxis.ActualMinimum);
- _settings.SetValue("plotPanel.MaxTimeSpan", (float)_timeAxis.ActualMaximum);
+ Position = AxisPosition.Left,
+ MajorGridlineStyle = LineStyle.Solid,
+ MajorGridlineThickness = 1,
+ MajorGridlineColor = _timeAxis.MajorGridlineColor,
+ MinorGridlineStyle = LineStyle.Solid,
+ MinorGridlineThickness = 1,
+ MinorGridlineColor = _timeAxis.MinorGridlineColor,
+ AxislineStyle = LineStyle.Solid,
+ Title = typeName,
+ Key = typeName,
+ };
+
+ var annotation = new LineAnnotation
+ {
+ Type = LineAnnotationType.Horizontal,
+ ClipByXAxis = false,
+ ClipByYAxis = false,
+ LineStyle = LineStyle.Solid,
+ Color = OxyColors.Black,
+ YAxisKey = typeName,
+ StrokeThickness = 2,
+ };
+
+ axis.AxisChanged += (sender, args) => annotation.Y = axis.ActualMinimum;
+ axis.TransformChanged += (sender, args) => annotation.Y = axis.ActualMinimum;
+
+ axis.Zoom(_settings.GetValue("plotPanel.Min" + axis.Key, float.NaN), _settings.GetValue("plotPanel.Max" + axis.Key, float.NaN));
+
+ if (units.ContainsKey(type))
+ axis.Unit = units[type];
+
+ _axes.Add(type, axis);
+ _annotations.Add(type, annotation);
}
- private ContextMenuStrip CreateMenu()
+ var model = new ScaledPlotModel(_dpiXScale, _dpiYScale);
+ model.Axes.Add(_timeAxis);
+ foreach (LinearAxis axis in _axes.Values)
+ model.Axes.Add(axis);
+ model.IsLegendVisible = false;
+
+ return model;
+ }
+
+ private void SetDpi()
+ {
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/dn469266(v=vs.85).aspx
+ const int defaultDpi = 96;
+ Graphics g = CreateGraphics();
+
+ try
{
- ContextMenuStrip menu = new ContextMenuStrip();
- menu.Opening += (sender, e) =>
- {
- if (_cancelContextMenu)
- {
- e.Cancel = true;
- _cancelContextMenu = false;
- }
- };
-
- ToolStripMenuItem stackedAxesMenuItem = new ToolStripMenuItem("Stacked Axes");
- _stackedAxes = new UserOption("stackedAxes", true, stackedAxesMenuItem, _settings);
- _stackedAxes.Changed += (sender, e) =>
- {
- UpdateAxesPosition();
- InvalidatePlot();
- };
- menu.Items.Add(stackedAxesMenuItem);
-
- ToolStripMenuItem showAxesLabelsMenuItem = new ToolStripMenuItem("Show Axes Labels");
- _showAxesLabels = new UserOption("showAxesLabels", true, showAxesLabelsMenuItem, _settings);
- _showAxesLabels.Changed += (sender, e) =>
- {
- if (_showAxesLabels.Value)
- _model.PlotMargins = new OxyThickness(double.NaN);
- else
- _model.PlotMargins = new OxyThickness(0);
- };
- menu.Items.Add(showAxesLabelsMenuItem);
-
- ToolStripMenuItem timeAxisMenuItem = new ToolStripMenuItem("Time Axis");
- ToolStripMenuItem[] timeAxisMenuItems =
- { new ToolStripMenuItem("Enable Zoom"),
- new ToolStripMenuItem("Auto", null, (s, e) => { TimeAxisZoom(0, double.NaN); }),
- new ToolStripMenuItem("5 min", null, (s, e) => { TimeAxisZoom(0, 5 * 60); }),
- new ToolStripMenuItem("10 min", null, (s, e) => { TimeAxisZoom(0, 10 * 60); }),
- new ToolStripMenuItem("20 min", null, (s, e) => { TimeAxisZoom(0, 20 * 60); }),
- new ToolStripMenuItem("30 min", null, (s, e) => { TimeAxisZoom(0, 30 * 60); }),
- new ToolStripMenuItem("45 min", null, (s, e) => { TimeAxisZoom(0, 45 * 60); }),
- new ToolStripMenuItem("1 h", null, (s, e) => { TimeAxisZoom(0, 60 * 60); }),
- new ToolStripMenuItem("1.5 h", null, (s, e) => { TimeAxisZoom(0, 1.5 * 60 * 60); }),
- new ToolStripMenuItem("2 h", null, (s, e) => { TimeAxisZoom(0, 2 * 60 * 60); }),
- new ToolStripMenuItem("3 h", null, (s, e) => { TimeAxisZoom(0, 3 * 60 * 60); }),
- new ToolStripMenuItem("6 h", null, (s, e) => { TimeAxisZoom(0, 6 * 60 * 60); }),
- new ToolStripMenuItem("12 h", null, (s, e) => { TimeAxisZoom(0, 12 * 60 * 60); }),
- new ToolStripMenuItem("24 h", null, (s, e) => { TimeAxisZoom(0, 24 * 60 * 60); }) };
-
- foreach (ToolStripItem mi in timeAxisMenuItems)
- timeAxisMenuItem.DropDownItems.Add(mi);
- menu.Items.Add(timeAxisMenuItem);
-
- _timeAxisEnableZoom = new UserOption("timeAxisEnableZoom", true, timeAxisMenuItems[0], _settings);
- _timeAxisEnableZoom.Changed += (sender, e) =>
- {
- _timeAxis.IsZoomEnabled = _timeAxisEnableZoom.Value;
- };
-
- ToolStripMenuItem yAxesMenuItem = new ToolStripMenuItem("Value Axes");
- ToolStripMenuItem[] yAxesMenuItems =
- { new ToolStripMenuItem("Enable Zoom"),
- new ToolStripMenuItem("Autoscale All", null, (s, e) => { AutoscaleAllYAxes(); }) };
-
- foreach (ToolStripItem mi in yAxesMenuItems)
- yAxesMenuItem.DropDownItems.Add(mi);
- menu.Items.Add(yAxesMenuItem);
-
- _yAxesEnableZoom = new UserOption("yAxesEnableZoom", true, yAxesMenuItems[0], _settings);
- _yAxesEnableZoom.Changed += (sender, e) =>
- {
- foreach (LinearAxis axis in _axes.Values)
- axis.IsZoomEnabled = _yAxesEnableZoom.Value;
- };
-
- return menu;
+ _dpiX = g.DpiX;
+ _dpiY = g.DpiY;
+ }
+ finally
+ {
+ g.Dispose();
}
- private PlotModel CreatePlotModel()
- {
- _timeAxis.Position = AxisPosition.Bottom;
- _timeAxis.MajorGridlineStyle = LineStyle.Solid;
- _timeAxis.MajorGridlineThickness = 1;
- _timeAxis.MajorGridlineColor = OxyColor.FromRgb(192, 192, 192);
- _timeAxis.MinorGridlineStyle = LineStyle.Solid;
- _timeAxis.MinorGridlineThickness = 1;
- _timeAxis.MinorGridlineColor = OxyColor.FromRgb(232, 232, 232);
- _timeAxis.StartPosition = 1;
- _timeAxis.EndPosition = 0;
- _timeAxis.MinimumPadding = 0;
- _timeAxis.MaximumPadding = 0;
- _timeAxis.AbsoluteMinimum = 0;
- _timeAxis.Minimum = 0;
- _timeAxis.AbsoluteMaximum = 24 * 60 * 60;
- _timeAxis.Zoom(
- _settings.GetValue("plotPanel.MinTimeSpan", 0.0f),
- _settings.GetValue("plotPanel.MaxTimeSpan", 10.0f * 60));
- _timeAxis.StringFormat = "h:mm";
+ if (_dpiX > 0)
+ _dpiXScale = _dpiX / defaultDpi;
+ if (_dpiY > 0)
+ _dpiYScale = _dpiY / defaultDpi;
+ }
- var units = new Dictionary
+ public void SetSensors(List sensors, IDictionary colors)
+ {
+ _model.Series.Clear();
+ var types = new HashSet();
+
+
+ DataPoint CreateDataPoint(SensorType type, SensorValue value)
+ {
+ float displayedValue;
+
+ if (type == SensorType.Temperature && _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit)
{
- { SensorType.Voltage, "V" },
- { SensorType.Current, "A" },
- { SensorType.Clock, "MHz" },
- { SensorType.Temperature, "°C" },
- { SensorType.Load, "%" },
- { SensorType.Fan, "RPM" },
- { SensorType.Flow, "L/h" },
- { SensorType.Control, "%" },
- { SensorType.Level, "%" },
- { SensorType.Factor, "1" },
- { SensorType.Power, "W" },
- { SensorType.Data, "GB" },
- { SensorType.Frequency, "Hz" },
- { SensorType.Energy, "mWh" },
- { SensorType.Noise, "dBA" }
+ displayedValue = UnitManager.CelsiusToFahrenheit(value.Value).Value;
+ }
+ else
+ {
+ displayedValue = value.Value;
+ }
+
+ return new DataPoint((_now - value.Time).TotalSeconds, displayedValue);
+ }
+
+
+ foreach (ISensor sensor in sensors)
+ {
+ var series = new LineSeries
+ {
+ ItemsSource = sensor.Values.Select(value => CreateDataPoint(sensor.SensorType, value)),
+ Color = colors[sensor].ToOxyColor(),
+ StrokeThickness = 1,
+ YAxisKey = _axes[sensor.SensorType].Key,
+ Title = sensor.Hardware.Name + " " + sensor.Name
};
- foreach (SensorType type in Enum.GetValues(typeof(SensorType)))
- {
- string typeName = type.ToString();
- var axis = new LinearAxis
- {
- Position = AxisPosition.Left,
- MajorGridlineStyle = LineStyle.Solid,
- MajorGridlineThickness = 1,
- MajorGridlineColor = _timeAxis.MajorGridlineColor,
- MinorGridlineStyle = LineStyle.Solid,
- MinorGridlineThickness = 1,
- MinorGridlineColor = _timeAxis.MinorGridlineColor,
- AxislineStyle = LineStyle.Solid,
- Title = typeName,
- Key = typeName,
- };
+ _model.Series.Add(series);
- var annotation = new LineAnnotation
- {
- Type = LineAnnotationType.Horizontal,
- ClipByXAxis = false,
- ClipByYAxis = false,
- LineStyle = LineStyle.Solid,
- Color = OxyColors.Black,
- YAxisKey = typeName,
- StrokeThickness = 2,
- };
-
- axis.AxisChanged += (sender, args) => annotation.Y = axis.ActualMinimum;
- axis.TransformChanged += (sender, args) => annotation.Y = axis.ActualMinimum;
-
- axis.Zoom(_settings.GetValue("plotPanel.Min" + axis.Key, float.NaN), _settings.GetValue("plotPanel.Max" + axis.Key, float.NaN));
-
- if (units.ContainsKey(type))
- axis.Unit = units[type];
-
- _axes.Add(type, axis);
- _annotations.Add(type, annotation);
- }
-
- var model = new ScaledPlotModel(_dpiXScale, _dpiYScale);
- model.Axes.Add(_timeAxis);
- foreach (LinearAxis axis in _axes.Values)
- model.Axes.Add(axis);
- model.IsLegendVisible = false;
-
- return model;
+ types.Add(sensor.SensorType);
}
- private void SetDpi()
+ foreach (KeyValuePair pair in _axes.Reverse())
{
- // https://msdn.microsoft.com/en-us/library/windows/desktop/dn469266(v=vs.85).aspx
- const int defaultDpi = 96;
- Graphics g = CreateGraphics();
-
- try
- {
- _dpiX = g.DpiX;
- _dpiY = g.DpiY;
- }
- finally
- {
- g.Dispose();
- }
-
- if (_dpiX > 0)
- _dpiXScale = _dpiX / defaultDpi;
- if (_dpiY > 0)
- _dpiYScale = _dpiY / defaultDpi;
+ LinearAxis axis = pair.Value;
+ SensorType type = pair.Key;
+ axis.IsAxisVisible = types.Contains(type);
}
- public void SetSensors(List sensors, IDictionary colors)
+ UpdateAxesPosition();
+ InvalidatePlot();
+ }
+
+ private void UpdateAxesPosition()
+ {
+ if (_stackedAxes.Value)
{
- _model.Series.Clear();
- var types = new HashSet();
-
-
- DataPoint CreateDataPoint(SensorType type, SensorValue value)
+ int count = _axes.Values.Count(axis => axis.IsAxisVisible);
+ double start = 0.0;
+ foreach (KeyValuePair pair in _axes.Reverse())
{
- float displayedValue;
-
- if (type == SensorType.Temperature && _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit)
- {
- displayedValue = UnitManager.CelsiusToFahrenheit(value.Value).Value;
- }
- else
- {
- displayedValue = value.Value;
- }
-
- return new DataPoint((_now - value.Time).TotalSeconds, displayedValue);
- }
-
-
- foreach (ISensor sensor in sensors)
- {
- var series = new LineSeries
- {
- ItemsSource = sensor.Values.Select(value => CreateDataPoint(sensor.SensorType, value)),
- Color = colors[sensor].ToOxyColor(),
- StrokeThickness = 1,
- YAxisKey = _axes[sensor.SensorType].Key,
- Title = sensor.Hardware.Name + " " + sensor.Name
- };
-
- _model.Series.Add(series);
-
- types.Add(sensor.SensorType);
+ LinearAxis axis = pair.Value;
+ axis.StartPosition = start;
+ double delta = axis.IsAxisVisible ? 1.0 / count : 0;
+ start += delta;
+ axis.EndPosition = start;
+ axis.PositionTier = 0;
+ axis.MajorGridlineStyle = LineStyle.Solid;
+ axis.MinorGridlineStyle = LineStyle.Solid;
+ LineAnnotation annotation = _annotations[pair.Key];
+ annotation.Y = axis.ActualMinimum;
+ if (!_model.Annotations.Contains(annotation))
+ _model.Annotations.Add(annotation);
}
+ }
+ else
+ {
+ int tier = 0;
foreach (KeyValuePair pair in _axes.Reverse())
{
LinearAxis axis = pair.Value;
- SensorType type = pair.Key;
- axis.IsAxisVisible = types.Contains(type);
- }
- UpdateAxesPosition();
- InvalidatePlot();
- }
-
- private void UpdateAxesPosition()
- {
- if (_stackedAxes.Value)
- {
- int count = _axes.Values.Count(axis => axis.IsAxisVisible);
- double start = 0.0;
- foreach (KeyValuePair pair in _axes.Reverse())
+ if (axis.IsAxisVisible)
{
- LinearAxis axis = pair.Value;
- axis.StartPosition = start;
- double delta = axis.IsAxisVisible ? 1.0 / count : 0;
- start += delta;
- axis.EndPosition = start;
+ axis.StartPosition = 0;
+ axis.EndPosition = 1;
+ axis.PositionTier = tier;
+ tier++;
+ }
+ else
+ {
+ axis.StartPosition = 0;
+ axis.EndPosition = 0;
axis.PositionTier = 0;
- axis.MajorGridlineStyle = LineStyle.Solid;
- axis.MinorGridlineStyle = LineStyle.Solid;
- LineAnnotation annotation = _annotations[pair.Key];
- annotation.Y = axis.ActualMinimum;
- if (!_model.Annotations.Contains(annotation))
- _model.Annotations.Add(annotation);
}
+ axis.MajorGridlineStyle = LineStyle.None;
+ axis.MinorGridlineStyle = LineStyle.None;
+ LineAnnotation annotation = _annotations[pair.Key];
+ if (_model.Annotations.Contains(annotation))
+ _model.Annotations.Remove(_annotations[pair.Key]);
}
- else
- {
- int tier = 0;
-
- foreach (KeyValuePair pair in _axes.Reverse())
- {
- LinearAxis axis = pair.Value;
-
- if (axis.IsAxisVisible)
- {
- axis.StartPosition = 0;
- axis.EndPosition = 1;
- axis.PositionTier = tier;
- tier++;
- }
- else
- {
- axis.StartPosition = 0;
- axis.EndPosition = 0;
- axis.PositionTier = 0;
- }
- axis.MajorGridlineStyle = LineStyle.None;
- axis.MinorGridlineStyle = LineStyle.None;
- LineAnnotation annotation = _annotations[pair.Key];
- if (_model.Annotations.Contains(annotation))
- _model.Annotations.Remove(_annotations[pair.Key]);
- }
- }
- }
-
- public void InvalidatePlot()
- {
- _now = DateTime.UtcNow;
-
- if (_axes != null)
- {
- foreach (KeyValuePair pair in _axes)
- {
- LinearAxis axis = pair.Value;
- SensorType type = pair.Key;
- if (type == SensorType.Temperature)
- axis.Unit = _unitManager.TemperatureUnit == TemperatureUnit.Celsius ? "°C" : "°F";
-
- if (!_stackedAxes.Value)
- continue;
-
- var annotation = _annotations[pair.Key];
- annotation.Y = axis.ActualMaximum;
- }
- }
-
- _plot?.InvalidatePlot(true);
- }
-
- public void TimeAxisZoom(double min, double max)
- {
- bool timeAxisIsZoomEnabled = _timeAxis.IsZoomEnabled;
-
- _timeAxis.IsZoomEnabled = true;
- _timeAxis.Zoom(min, max);
- InvalidatePlot();
- _timeAxis.IsZoomEnabled = timeAxisIsZoomEnabled;
- }
-
- public void AutoscaleAllYAxes()
- {
- foreach (LinearAxis axis in _axes.Values)
- axis.Zoom(double.NaN, double.NaN);
}
}
-}
+
+ public void InvalidatePlot()
+ {
+ _now = DateTime.UtcNow;
+
+ if (_axes != null)
+ {
+ foreach (KeyValuePair pair in _axes)
+ {
+ LinearAxis axis = pair.Value;
+ SensorType type = pair.Key;
+ if (type == SensorType.Temperature)
+ axis.Unit = _unitManager.TemperatureUnit == TemperatureUnit.Celsius ? "°C" : "°F";
+
+ if (!_stackedAxes.Value)
+ continue;
+
+ var annotation = _annotations[pair.Key];
+ annotation.Y = axis.ActualMaximum;
+ }
+ }
+
+ _plot?.InvalidatePlot(true);
+ }
+
+ public void TimeAxisZoom(double min, double max)
+ {
+ bool timeAxisIsZoomEnabled = _timeAxis.IsZoomEnabled;
+
+ _timeAxis.IsZoomEnabled = true;
+ _timeAxis.Zoom(min, max);
+ InvalidatePlot();
+ _timeAxis.IsZoomEnabled = timeAxisIsZoomEnabled;
+ }
+
+ public void AutoscaleAllYAxes()
+ {
+ foreach (LinearAxis axis in _axes.Values)
+ axis.Zoom(double.NaN, double.NaN);
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/PortForm.cs b/LibreHardwareMonitor/UI/PortForm.cs
index 22d9c4e..e30d57b 100644
--- a/LibreHardwareMonitor/UI/PortForm.cs
+++ b/LibreHardwareMonitor/UI/PortForm.cs
@@ -10,74 +10,73 @@ using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public partial class PortForm : Form
{
- public partial class PortForm : Form
+ private readonly MainForm _parent;
+ private readonly string _localIP;
+ public PortForm(MainForm m)
{
- private readonly MainForm _parent;
- private readonly string _localIP;
- public PortForm(MainForm m)
- {
- InitializeComponent();
- _parent = m;
- _localIP = GetLocalIP();
- }
-
- private void PortTextBox_TextChanged(object sender, EventArgs e)
- {
-
- }
-
- private string GetLocalIP()
- {
- IPHostEntry host;
- string localIP = "?";
- host = Dns.GetHostEntry(Dns.GetHostName());
- foreach (IPAddress ip in host.AddressList)
- {
- if (ip.AddressFamily == AddressFamily.InterNetwork)
- localIP = ip.ToString();
- }
- return localIP;
- }
-
- private void PortNumericUpDn_ValueChanged(object sender, EventArgs e)
- {
- string url = "http://" + _localIP + ":" + portNumericUpDn.Value + "/";
- webServerLinkLabel.Text = url;
- webServerLinkLabel.Links.Remove(webServerLinkLabel.Links[0]);
- webServerLinkLabel.Links.Add(0, webServerLinkLabel.Text.Length, url);
- }
-
- private void PortOKButton_Click(object sender, EventArgs e)
- {
- _parent.Server.ListenerPort = (int)portNumericUpDn.Value;
- Close();
- }
-
- private void PortCancelButton_Click(object sender, EventArgs e)
- {
- Close();
- }
-
- private void PortForm_Load(object sender, EventArgs e)
- {
- portNumericUpDn.Value = _parent.Server.ListenerPort;
- PortNumericUpDn_ValueChanged(null, null);
- }
-
- private void WebServerLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
- {
- try
- {
- Process.Start(new ProcessStartInfo(e.Link.LinkData.ToString()));
- }
- catch { }
- }
-
- private void PortNumericUpDn_KeyUp(object sender, KeyEventArgs e)
- {
- PortNumericUpDn_ValueChanged(null, null);
- }
+ InitializeComponent();
+ _parent = m;
+ _localIP = GetLocalIP();
}
-}
+
+ private void PortTextBox_TextChanged(object sender, EventArgs e)
+ {
+
+ }
+
+ private string GetLocalIP()
+ {
+ IPHostEntry host;
+ string localIP = "?";
+ host = Dns.GetHostEntry(Dns.GetHostName());
+ foreach (IPAddress ip in host.AddressList)
+ {
+ if (ip.AddressFamily == AddressFamily.InterNetwork)
+ localIP = ip.ToString();
+ }
+ return localIP;
+ }
+
+ private void PortNumericUpDn_ValueChanged(object sender, EventArgs e)
+ {
+ string url = "http://" + _localIP + ":" + portNumericUpDn.Value + "/";
+ webServerLinkLabel.Text = url;
+ webServerLinkLabel.Links.Remove(webServerLinkLabel.Links[0]);
+ webServerLinkLabel.Links.Add(0, webServerLinkLabel.Text.Length, url);
+ }
+
+ private void PortOKButton_Click(object sender, EventArgs e)
+ {
+ _parent.Server.ListenerPort = (int)portNumericUpDn.Value;
+ Close();
+ }
+
+ private void PortCancelButton_Click(object sender, EventArgs e)
+ {
+ Close();
+ }
+
+ private void PortForm_Load(object sender, EventArgs e)
+ {
+ portNumericUpDn.Value = _parent.Server.ListenerPort;
+ PortNumericUpDn_ValueChanged(null, null);
+ }
+
+ private void WebServerLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
+ {
+ try
+ {
+ Process.Start(new ProcessStartInfo(e.Link.LinkData.ToString()));
+ }
+ catch { }
+ }
+
+ private void PortNumericUpDn_KeyUp(object sender, KeyEventArgs e)
+ {
+ PortNumericUpDn_ValueChanged(null, null);
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/ScaledPlotModel.cs b/LibreHardwareMonitor/UI/ScaledPlotModel.cs
index 39352be..eb02187 100644
--- a/LibreHardwareMonitor/UI/ScaledPlotModel.cs
+++ b/LibreHardwareMonitor/UI/ScaledPlotModel.cs
@@ -1,34 +1,33 @@
using OxyPlot;
using OxyPlot.Legends;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+class ScaledPlotModel : PlotModel
{
- class ScaledPlotModel : PlotModel
+ public ScaledPlotModel(double dpiXscale, double dpiYscale)
{
- public ScaledPlotModel(double dpiXscale, double dpiYscale)
- {
- PlotMargins = new OxyThickness(PlotMargins.Left * dpiXscale,
- PlotMargins.Top * dpiYscale,
- PlotMargins.Right * dpiXscale,
- PlotMargins.Bottom * dpiYscale);
+ PlotMargins = new OxyThickness(PlotMargins.Left * dpiXscale,
+ PlotMargins.Top * dpiYscale,
+ PlotMargins.Right * dpiXscale,
+ PlotMargins.Bottom * dpiYscale);
- Padding = new OxyThickness(Padding.Left * dpiXscale,
- Padding.Top * dpiYscale,
- Padding.Right * dpiXscale,
- Padding.Bottom * dpiYscale);
+ Padding = new OxyThickness(Padding.Left * dpiXscale,
+ Padding.Top * dpiYscale,
+ Padding.Right * dpiXscale,
+ Padding.Bottom * dpiYscale);
- TitlePadding *= dpiXscale;
+ TitlePadding *= dpiXscale;
- Legend legend = new();
+ Legend legend = new();
- legend.LegendSymbolLength *= dpiXscale;
- legend.LegendSymbolMargin *= dpiXscale;
- legend.LegendPadding *= dpiXscale;
- legend.LegendColumnSpacing *= dpiXscale;
- legend.LegendItemSpacing *= dpiXscale;
- legend.LegendMargin *= dpiXscale;
+ legend.LegendSymbolLength *= dpiXscale;
+ legend.LegendSymbolMargin *= dpiXscale;
+ legend.LegendPadding *= dpiXscale;
+ legend.LegendColumnSpacing *= dpiXscale;
+ legend.LegendItemSpacing *= dpiXscale;
+ legend.LegendMargin *= dpiXscale;
- Legends.Add(legend);
- }
+ Legends.Add(legend);
}
-}
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/SensorGadget.cs b/LibreHardwareMonitor/UI/SensorGadget.cs
index 07f0872..7c3b055 100644
--- a/LibreHardwareMonitor/UI/SensorGadget.cs
+++ b/LibreHardwareMonitor/UI/SensorGadget.cs
@@ -14,743 +14,741 @@ using System.Linq;
using LibreHardwareMonitor.Hardware;
using LibreHardwareMonitor.Utilities;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class SensorGadget : Gadget
{
- public class SensorGadget : Gadget
+ private const int TopBorder = 6;
+ private const int BottomBorder = 7;
+ private const int LeftBorder = 6;
+ private const int RightBorder = 7;
+
+ private readonly UnitManager _unitManager;
+ private Image _back = Utilities.EmbeddedResources.GetImage("gadget.png");
+ private Image _image;
+ private Image _fore;
+ private Image _barBack = Utilities.EmbeddedResources.GetImage("barback.png");
+ private Image _barFore = Utilities.EmbeddedResources.GetImage("barblue.png");
+ private Image _background = new Bitmap(1, 1);
+ private readonly float _scale;
+ private float _fontSize;
+ private int _iconSize;
+ private int _hardwareLineHeight;
+ private int _sensorLineHeight;
+ private int _rightMargin;
+ private int _leftMargin;
+ private int _topMargin;
+ private int _bottomMargin;
+ private int _progressWidth;
+
+ private readonly IDictionary> _sensors = new SortedDictionary>(new HardwareComparer());
+ private readonly PersistentSettings _settings;
+ private readonly UserOption _hardwareNames;
+
+ private Font _largeFont;
+ private Font _smallFont;
+ private Brush _textBrush;
+ private StringFormat _stringFormat;
+ private StringFormat _trimStringFormat;
+ private StringFormat _alignRightStringFormat;
+
+ public SensorGadget(IComputer computer, PersistentSettings settings, UnitManager unitManager)
{
- private const int TopBorder = 6;
- private const int BottomBorder = 7;
- private const int LeftBorder = 6;
- private const int RightBorder = 7;
+ _unitManager = unitManager;
+ _settings = settings;
+ computer.HardwareAdded += HardwareAdded;
+ computer.HardwareRemoved += HardwareRemoved;
- private readonly UnitManager _unitManager;
- private Image _back = Utilities.EmbeddedResources.GetImage("gadget.png");
- private Image _image;
- private Image _fore;
- private Image _barBack = Utilities.EmbeddedResources.GetImage("barback.png");
- private Image _barFore = Utilities.EmbeddedResources.GetImage("barblue.png");
- private Image _background = new Bitmap(1, 1);
- private readonly float _scale;
- private float _fontSize;
- private int _iconSize;
- private int _hardwareLineHeight;
- private int _sensorLineHeight;
- private int _rightMargin;
- private int _leftMargin;
- private int _topMargin;
- private int _bottomMargin;
- private int _progressWidth;
+ _stringFormat = new StringFormat { FormatFlags = StringFormatFlags.NoWrap };
+ _trimStringFormat = new StringFormat { Trimming = StringTrimming.EllipsisCharacter, FormatFlags = StringFormatFlags.NoWrap };
+ _alignRightStringFormat = new StringFormat { Alignment = StringAlignment.Far, FormatFlags = StringFormatFlags.NoWrap };
- private readonly IDictionary> _sensors = new SortedDictionary>(new HardwareComparer());
- private readonly PersistentSettings _settings;
- private readonly UserOption _hardwareNames;
-
- private Font _largeFont;
- private Font _smallFont;
- private Brush _textBrush;
- private StringFormat _stringFormat;
- private StringFormat _trimStringFormat;
- private StringFormat _alignRightStringFormat;
-
- public SensorGadget(IComputer computer, PersistentSettings settings, UnitManager unitManager)
- {
- _unitManager = unitManager;
- _settings = settings;
- computer.HardwareAdded += HardwareAdded;
- computer.HardwareRemoved += HardwareRemoved;
-
- _stringFormat = new StringFormat { FormatFlags = StringFormatFlags.NoWrap };
- _trimStringFormat = new StringFormat { Trimming = StringTrimming.EllipsisCharacter, FormatFlags = StringFormatFlags.NoWrap };
- _alignRightStringFormat = new StringFormat { Alignment = StringAlignment.Far, FormatFlags = StringFormatFlags.NoWrap };
-
- if (File.Exists("gadget_background.png"))
- {
- try
- {
- Image newBack = new Bitmap("gadget_background.png");
- _back.Dispose();
- _back = newBack;
- }
- catch { }
- }
-
- if (File.Exists("gadget_image.png"))
- {
- try
- {
- _image = new Bitmap("gadget_image.png");
- }
- catch { }
- }
-
- if (File.Exists("gadget_foreground.png"))
- {
- try
- {
- _fore = new Bitmap("gadget_foreground.png");
- }
- catch { }
- }
-
- if (File.Exists("gadget_bar_background.png"))
- {
- try
- {
- Image newBarBack = new Bitmap("gadget_bar_background.png");
- _barBack.Dispose();
- _barBack = newBarBack;
- }
- catch { }
- }
-
- if (File.Exists("gadget_bar_foreground.png"))
- {
- try
- {
- Image newBarColor = new Bitmap("gadget_bar_foreground.png");
- _barFore.Dispose();
- _barFore = newBarColor;
- }
- catch { }
- }
-
- Location = new Point(settings.GetValue("sensorGadget.Location.X", 100), settings.GetValue("sensorGadget.Location.Y", 100));
- LocationChanged += delegate
- {
- settings.SetValue("sensorGadget.Location.X", Location.X);
- settings.SetValue("sensorGadget.Location.Y", Location.Y);
- };
-
- // get the custom to default dpi ratio
- using (Bitmap b = new Bitmap(1, 1))
- {
- _scale = b.HorizontalResolution / 96.0f;
- }
-
- SetFontSize(settings.GetValue("sensorGadget.FontSize", 7.5f));
- Resize(settings.GetValue("sensorGadget.Width", Size.Width));
-
- ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
- ToolStripMenuItem hardwareNamesItem = new ToolStripMenuItem("Hardware Names");
- contextMenuStrip.Items.Add(hardwareNamesItem);
- ToolStripMenuItem fontSizeMenu = new ToolStripMenuItem("Font Size");
- for (int i = 0; i < 4; i++)
- {
- float size;
- string name;
- switch (i)
- {
- case 0: size = 6.5f; name = "Small"; break;
- case 1: size = 7.5f; name = "Medium"; break;
- case 2: size = 9f; name = "Large"; break;
- case 3: size = 11f; name = "Very Large"; break;
- default: throw new NotImplementedException();
- }
-
- ToolStripItem item = new ToolStripMenuItem(name) { Checked = _fontSize == size };
- item.Click += delegate
- {
- SetFontSize(size);
- settings.SetValue("sensorGadget.FontSize", size);
- foreach (ToolStripMenuItem mi in fontSizeMenu.DropDownItems)
- mi.Checked = mi == item;
- };
- fontSizeMenu.DropDownItems.Add(item);
- }
- contextMenuStrip.Items.Add(fontSizeMenu);
-
- Color fontColor = settings.GetValue("sensorGadget.FontColor", Color.White);
- int fontColorArgb = fontColor.ToArgb();
-
- SetFontColor(fontColor);
-
- IEnumerable providedColors = Enum.GetValues(typeof(KnownColor))
- .Cast()
- .Select(x => Color.FromKnownColor(x))
- .Where(x => !x.IsSystemColor && x.Name.Length < 7);
-
- ToolStripMenuItem fontColorMenu = new ToolStripMenuItem("Font Color");
- foreach (Color color in providedColors)
- {
- ToolStripItem item = new ToolStripMenuItem(color.Name) { Checked = fontColorArgb == color.ToArgb() };
- item.Click += delegate
- {
- SetFontColor(color);
- settings.SetValue("sensorGadget.FontColor", color);
- foreach (ToolStripMenuItem mi in fontColorMenu.DropDownItems)
- mi.Checked = mi == item;
- };
- fontColorMenu.DropDownItems.Add(item);
- }
- contextMenuStrip.Items.Add(fontColorMenu);
- contextMenuStrip.Items.Add(new ToolStripSeparator());
- ToolStripMenuItem lockItem = new ToolStripMenuItem("Lock Position and Size");
- contextMenuStrip.Items.Add(lockItem);
- contextMenuStrip.Items.Add(new ToolStripSeparator());
- ToolStripMenuItem alwaysOnTopItem = new ToolStripMenuItem("Always on Top");
- contextMenuStrip.Items.Add(alwaysOnTopItem);
- ToolStripMenuItem opacityMenu = new ToolStripMenuItem("Opacity");
- contextMenuStrip.Items.Add(opacityMenu);
- Opacity = (byte)settings.GetValue("sensorGadget.Opacity", 255);
-
- for (int i = 0; i < 5; i++)
- {
- ToolStripMenuItem item = new ToolStripMenuItem((20 * (i + 1)).ToString() + " %");
- byte o = (byte)(51 * (i + 1));
- item.Checked = Opacity == o;
- item.Click += delegate
- {
- Opacity = o;
- settings.SetValue("sensorGadget.Opacity", Opacity);
- foreach (ToolStripMenuItem mi in opacityMenu.DropDownItems)
- mi.Checked = mi == item;
- };
- opacityMenu.DropDownItems.Add(item);
- }
- ContextMenuStrip = contextMenuStrip;
-
- _hardwareNames = new UserOption("sensorGadget.Hardwarenames", true, hardwareNamesItem, settings);
- _hardwareNames.Changed += delegate
- {
- Resize();
- };
-
- UserOption alwaysOnTop = new UserOption("sensorGadget.AlwaysOnTop", false, alwaysOnTopItem, settings);
- alwaysOnTop.Changed += delegate
- {
- AlwaysOnTop = alwaysOnTop.Value;
- };
- UserOption lockPositionAndSize = new UserOption("sensorGadget.LockPositionAndSize", false, lockItem, settings);
- lockPositionAndSize.Changed += delegate
- {
- LockPositionAndSize = lockPositionAndSize.Value;
- };
-
- HitTest += delegate (object sender, HitTestEventArgs e)
- {
- if (lockPositionAndSize.Value)
- return;
-
- if (e.Location.X < LeftBorder)
- {
- e.HitResult = HitResult.Left;
- return;
- }
- if (e.Location.X > Size.Width - 1 - RightBorder)
- {
- e.HitResult = HitResult.Right;
- }
- };
-
- SizeChanged += delegate
- {
- settings.SetValue("sensorGadget.Width", Size.Width);
- Redraw();
- };
-
- VisibleChanged += delegate
- {
- Rectangle bounds = new Rectangle(Location, Size);
- Screen screen = Screen.FromRectangle(bounds);
- Rectangle intersection = Rectangle.Intersect(screen.WorkingArea, bounds);
- if (intersection.Width < Math.Min(16, bounds.Width) || intersection.Height < Math.Min(16, bounds.Height))
- {
- Location = new Point(screen.WorkingArea.Width / 2 - bounds.Width / 2, screen.WorkingArea.Height / 2 - bounds.Height / 2);
- }
- };
-
- MouseDoubleClick += delegate
- {
- SendHideShowCommand();
- };
- }
-
- public override void Dispose()
- {
-
- _largeFont.Dispose();
- _largeFont = null;
-
- _smallFont.Dispose();
- _smallFont = null;
-
- _textBrush.Dispose();
- _textBrush = null;
-
- _stringFormat.Dispose();
- _stringFormat = null;
-
- _trimStringFormat.Dispose();
- _trimStringFormat = null;
-
- _alignRightStringFormat.Dispose();
- _alignRightStringFormat = null;
-
- _back.Dispose();
- _back = null;
-
- _barFore.Dispose();
- _barFore = null;
-
- _barBack.Dispose();
- _barBack = null;
-
- _background.Dispose();
- _background = null;
-
- if (_image != null)
- {
- _image.Dispose();
- _image = null;
- }
-
- if (_fore != null)
- {
- _fore.Dispose();
- _fore = null;
- }
-
- base.Dispose();
- }
-
- private void HardwareRemoved(IHardware hardware)
- {
- hardware.SensorAdded -= SensorAdded;
- hardware.SensorRemoved -= SensorRemoved;
-
- foreach (ISensor sensor in hardware.Sensors)
- SensorRemoved(sensor);
-
- foreach (IHardware subHardware in hardware.SubHardware)
- HardwareRemoved(subHardware);
- }
-
- private void HardwareAdded(IHardware hardware)
- {
- foreach (ISensor sensor in hardware.Sensors)
- SensorAdded(sensor);
-
- hardware.SensorAdded += SensorAdded;
- hardware.SensorRemoved += SensorRemoved;
-
- foreach (IHardware subHardware in hardware.SubHardware)
- HardwareAdded(subHardware);
- }
-
- private void SensorAdded(ISensor sensor)
- {
- if (_settings.GetValue(new Identifier(sensor.Identifier, "gadget").ToString(), false))
- Add(sensor);
- }
-
- private void SensorRemoved(ISensor sensor)
- {
- if (Contains(sensor))
- Remove(sensor, false);
- }
-
- public bool Contains(ISensor sensor)
- {
- return _sensors.Values.Any(list => list.Contains(sensor));
- }
-
- public void Add(ISensor sensor)
- {
- if (Contains(sensor))
- return;
-
-
- // get the right hardware
- IHardware hardware = sensor.Hardware;
- while (hardware.Parent != null)
- hardware = hardware.Parent;
-
- // get the sensor list associated with the hardware
- if (!_sensors.TryGetValue(hardware, out IList list))
- {
- list = new List();
- _sensors.Add(hardware, list);
- }
-
- // insert the sensor at the right position
- int i = 0;
- while (i < list.Count && (list[i].SensorType < sensor.SensorType || (list[i].SensorType == sensor.SensorType && list[i].Index < sensor.Index)))
- i++;
-
- list.Insert(i, sensor);
-
- _settings.SetValue(new Identifier(sensor.Identifier, "gadget").ToString(), true);
- Resize();
- }
-
- public void Remove(ISensor sensor)
- {
- Remove(sensor, true);
- }
-
- private void Remove(ISensor sensor, bool deleteConfig)
- {
- if (deleteConfig)
- _settings.Remove(new Identifier(sensor.Identifier, "gadget").ToString());
-
- foreach (KeyValuePair> keyValue in _sensors)
- {
- if (keyValue.Value.Contains(sensor))
- {
- keyValue.Value.Remove(sensor);
- if (keyValue.Value.Count == 0)
- {
- _sensors.Remove(keyValue.Key);
- break;
- }
- }
- }
- Resize();
- }
-
- public event EventHandler HideShowCommand;
-
- public void SendHideShowCommand()
- {
- HideShowCommand?.Invoke(this, null);
- }
-
- private Font CreateFont(float size, FontStyle style)
+ if (File.Exists("gadget_background.png"))
{
try
{
- return new Font(SystemFonts.MessageBoxFont.FontFamily, size, style);
+ Image newBack = new Bitmap("gadget_background.png");
+ _back.Dispose();
+ _back = newBack;
}
- catch (ArgumentException)
+ catch { }
+ }
+
+ if (File.Exists("gadget_image.png"))
+ {
+ try
{
- // if the style is not supported, fall back to the original one
- return new Font(SystemFonts.MessageBoxFont.FontFamily, size,
- SystemFonts.MessageBoxFont.Style);
+ _image = new Bitmap("gadget_image.png");
}
+ catch { }
}
- private void SetFontSize(float size)
+ if (File.Exists("gadget_foreground.png"))
{
- _fontSize = size;
- _largeFont = CreateFont(_fontSize, FontStyle.Bold);
- _smallFont = CreateFont(_fontSize, FontStyle.Regular);
-
- double scaledFontSize = _fontSize * _scale;
- _iconSize = (int)Math.Round(1.5 * scaledFontSize);
- _hardwareLineHeight = (int)Math.Round(1.66 * scaledFontSize);
- _sensorLineHeight = (int)Math.Round(1.33 * scaledFontSize);
- _leftMargin = LeftBorder + (int)Math.Round(0.3 * scaledFontSize);
- _rightMargin = RightBorder + (int)Math.Round(0.3 * scaledFontSize);
- _topMargin = TopBorder;
- _bottomMargin = BottomBorder + (int)Math.Round(0.3 * scaledFontSize);
- _progressWidth = (int)Math.Round(5.3 * scaledFontSize);
-
- Resize((int)Math.Round(17.3 * scaledFontSize));
- }
-
- private void SetFontColor(Color color)
- {
- _textBrush?.Dispose();
- _textBrush = new SolidBrush(color);
- }
-
- private void Resize()
- {
- Resize(Size.Width);
- }
-
- private void Resize(int width)
- {
- int y = _topMargin;
-
- foreach (KeyValuePair> pair in _sensors)
+ try
{
- if (_hardwareNames.Value)
+ _fore = new Bitmap("gadget_foreground.png");
+ }
+ catch { }
+ }
+
+ if (File.Exists("gadget_bar_background.png"))
+ {
+ try
+ {
+ Image newBarBack = new Bitmap("gadget_bar_background.png");
+ _barBack.Dispose();
+ _barBack = newBarBack;
+ }
+ catch { }
+ }
+
+ if (File.Exists("gadget_bar_foreground.png"))
+ {
+ try
+ {
+ Image newBarColor = new Bitmap("gadget_bar_foreground.png");
+ _barFore.Dispose();
+ _barFore = newBarColor;
+ }
+ catch { }
+ }
+
+ Location = new Point(settings.GetValue("sensorGadget.Location.X", 100), settings.GetValue("sensorGadget.Location.Y", 100));
+ LocationChanged += delegate
+ {
+ settings.SetValue("sensorGadget.Location.X", Location.X);
+ settings.SetValue("sensorGadget.Location.Y", Location.Y);
+ };
+
+ // get the custom to default dpi ratio
+ using (Bitmap b = new Bitmap(1, 1))
+ {
+ _scale = b.HorizontalResolution / 96.0f;
+ }
+
+ SetFontSize(settings.GetValue("sensorGadget.FontSize", 7.5f));
+ Resize(settings.GetValue("sensorGadget.Width", Size.Width));
+
+ ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
+ ToolStripMenuItem hardwareNamesItem = new ToolStripMenuItem("Hardware Names");
+ contextMenuStrip.Items.Add(hardwareNamesItem);
+ ToolStripMenuItem fontSizeMenu = new ToolStripMenuItem("Font Size");
+ for (int i = 0; i < 4; i++)
+ {
+ float size;
+ string name;
+ switch (i)
+ {
+ case 0: size = 6.5f; name = "Small"; break;
+ case 1: size = 7.5f; name = "Medium"; break;
+ case 2: size = 9f; name = "Large"; break;
+ case 3: size = 11f; name = "Very Large"; break;
+ default: throw new NotImplementedException();
+ }
+
+ ToolStripItem item = new ToolStripMenuItem(name) { Checked = _fontSize == size };
+ item.Click += delegate
+ {
+ SetFontSize(size);
+ settings.SetValue("sensorGadget.FontSize", size);
+ foreach (ToolStripMenuItem mi in fontSizeMenu.DropDownItems)
+ mi.Checked = mi == item;
+ };
+ fontSizeMenu.DropDownItems.Add(item);
+ }
+ contextMenuStrip.Items.Add(fontSizeMenu);
+
+ Color fontColor = settings.GetValue("sensorGadget.FontColor", Color.White);
+ int fontColorArgb = fontColor.ToArgb();
+
+ SetFontColor(fontColor);
+
+ IEnumerable providedColors = Enum.GetValues(typeof(KnownColor))
+ .Cast()
+ .Select(x => Color.FromKnownColor(x))
+ .Where(x => !x.IsSystemColor && x.Name.Length < 7);
+
+ ToolStripMenuItem fontColorMenu = new ToolStripMenuItem("Font Color");
+ foreach (Color color in providedColors)
+ {
+ ToolStripItem item = new ToolStripMenuItem(color.Name) { Checked = fontColorArgb == color.ToArgb() };
+ item.Click += delegate
+ {
+ SetFontColor(color);
+ settings.SetValue("sensorGadget.FontColor", color);
+ foreach (ToolStripMenuItem mi in fontColorMenu.DropDownItems)
+ mi.Checked = mi == item;
+ };
+ fontColorMenu.DropDownItems.Add(item);
+ }
+ contextMenuStrip.Items.Add(fontColorMenu);
+ contextMenuStrip.Items.Add(new ToolStripSeparator());
+ ToolStripMenuItem lockItem = new ToolStripMenuItem("Lock Position and Size");
+ contextMenuStrip.Items.Add(lockItem);
+ contextMenuStrip.Items.Add(new ToolStripSeparator());
+ ToolStripMenuItem alwaysOnTopItem = new ToolStripMenuItem("Always on Top");
+ contextMenuStrip.Items.Add(alwaysOnTopItem);
+ ToolStripMenuItem opacityMenu = new ToolStripMenuItem("Opacity");
+ contextMenuStrip.Items.Add(opacityMenu);
+ Opacity = (byte)settings.GetValue("sensorGadget.Opacity", 255);
+
+ for (int i = 0; i < 5; i++)
+ {
+ ToolStripMenuItem item = new ToolStripMenuItem((20 * (i + 1)).ToString() + " %");
+ byte o = (byte)(51 * (i + 1));
+ item.Checked = Opacity == o;
+ item.Click += delegate
+ {
+ Opacity = o;
+ settings.SetValue("sensorGadget.Opacity", Opacity);
+ foreach (ToolStripMenuItem mi in opacityMenu.DropDownItems)
+ mi.Checked = mi == item;
+ };
+ opacityMenu.DropDownItems.Add(item);
+ }
+ ContextMenuStrip = contextMenuStrip;
+
+ _hardwareNames = new UserOption("sensorGadget.Hardwarenames", true, hardwareNamesItem, settings);
+ _hardwareNames.Changed += delegate
+ {
+ Resize();
+ };
+
+ UserOption alwaysOnTop = new UserOption("sensorGadget.AlwaysOnTop", false, alwaysOnTopItem, settings);
+ alwaysOnTop.Changed += delegate
+ {
+ AlwaysOnTop = alwaysOnTop.Value;
+ };
+ UserOption lockPositionAndSize = new UserOption("sensorGadget.LockPositionAndSize", false, lockItem, settings);
+ lockPositionAndSize.Changed += delegate
+ {
+ LockPositionAndSize = lockPositionAndSize.Value;
+ };
+
+ HitTest += delegate (object sender, HitTestEventArgs e)
+ {
+ if (lockPositionAndSize.Value)
+ return;
+
+ if (e.Location.X < LeftBorder)
+ {
+ e.HitResult = HitResult.Left;
+ return;
+ }
+ if (e.Location.X > Size.Width - 1 - RightBorder)
+ {
+ e.HitResult = HitResult.Right;
+ }
+ };
+
+ SizeChanged += delegate
+ {
+ settings.SetValue("sensorGadget.Width", Size.Width);
+ Redraw();
+ };
+
+ VisibleChanged += delegate
+ {
+ Rectangle bounds = new Rectangle(Location, Size);
+ Screen screen = Screen.FromRectangle(bounds);
+ Rectangle intersection = Rectangle.Intersect(screen.WorkingArea, bounds);
+ if (intersection.Width < Math.Min(16, bounds.Width) || intersection.Height < Math.Min(16, bounds.Height))
+ {
+ Location = new Point(screen.WorkingArea.Width / 2 - bounds.Width / 2, screen.WorkingArea.Height / 2 - bounds.Height / 2);
+ }
+ };
+
+ MouseDoubleClick += delegate
+ {
+ SendHideShowCommand();
+ };
+ }
+
+ public override void Dispose()
+ {
+
+ _largeFont.Dispose();
+ _largeFont = null;
+
+ _smallFont.Dispose();
+ _smallFont = null;
+
+ _textBrush.Dispose();
+ _textBrush = null;
+
+ _stringFormat.Dispose();
+ _stringFormat = null;
+
+ _trimStringFormat.Dispose();
+ _trimStringFormat = null;
+
+ _alignRightStringFormat.Dispose();
+ _alignRightStringFormat = null;
+
+ _back.Dispose();
+ _back = null;
+
+ _barFore.Dispose();
+ _barFore = null;
+
+ _barBack.Dispose();
+ _barBack = null;
+
+ _background.Dispose();
+ _background = null;
+
+ if (_image != null)
+ {
+ _image.Dispose();
+ _image = null;
+ }
+
+ if (_fore != null)
+ {
+ _fore.Dispose();
+ _fore = null;
+ }
+
+ base.Dispose();
+ }
+
+ private void HardwareRemoved(IHardware hardware)
+ {
+ hardware.SensorAdded -= SensorAdded;
+ hardware.SensorRemoved -= SensorRemoved;
+
+ foreach (ISensor sensor in hardware.Sensors)
+ SensorRemoved(sensor);
+
+ foreach (IHardware subHardware in hardware.SubHardware)
+ HardwareRemoved(subHardware);
+ }
+
+ private void HardwareAdded(IHardware hardware)
+ {
+ foreach (ISensor sensor in hardware.Sensors)
+ SensorAdded(sensor);
+
+ hardware.SensorAdded += SensorAdded;
+ hardware.SensorRemoved += SensorRemoved;
+
+ foreach (IHardware subHardware in hardware.SubHardware)
+ HardwareAdded(subHardware);
+ }
+
+ private void SensorAdded(ISensor sensor)
+ {
+ if (_settings.GetValue(new Identifier(sensor.Identifier, "gadget").ToString(), false))
+ Add(sensor);
+ }
+
+ private void SensorRemoved(ISensor sensor)
+ {
+ if (Contains(sensor))
+ Remove(sensor, false);
+ }
+
+ public bool Contains(ISensor sensor)
+ {
+ return _sensors.Values.Any(list => list.Contains(sensor));
+ }
+
+ public void Add(ISensor sensor)
+ {
+ if (Contains(sensor))
+ return;
+
+
+ // get the right hardware
+ IHardware hardware = sensor.Hardware;
+ while (hardware.Parent != null)
+ hardware = hardware.Parent;
+
+ // get the sensor list associated with the hardware
+ if (!_sensors.TryGetValue(hardware, out IList list))
+ {
+ list = new List();
+ _sensors.Add(hardware, list);
+ }
+
+ // insert the sensor at the right position
+ int i = 0;
+ while (i < list.Count && (list[i].SensorType < sensor.SensorType || (list[i].SensorType == sensor.SensorType && list[i].Index < sensor.Index)))
+ i++;
+
+ list.Insert(i, sensor);
+
+ _settings.SetValue(new Identifier(sensor.Identifier, "gadget").ToString(), true);
+ Resize();
+ }
+
+ public void Remove(ISensor sensor)
+ {
+ Remove(sensor, true);
+ }
+
+ private void Remove(ISensor sensor, bool deleteConfig)
+ {
+ if (deleteConfig)
+ _settings.Remove(new Identifier(sensor.Identifier, "gadget").ToString());
+
+ foreach (KeyValuePair> keyValue in _sensors)
+ {
+ if (keyValue.Value.Contains(sensor))
+ {
+ keyValue.Value.Remove(sensor);
+ if (keyValue.Value.Count == 0)
{
- if (y > _topMargin)
- y += _hardwareLineHeight - _sensorLineHeight;
- y += _hardwareLineHeight;
+ _sensors.Remove(keyValue.Key);
+ break;
}
- y += pair.Value.Count * _sensorLineHeight;
}
-
- if (_sensors.Count == 0)
- y += 4 * _sensorLineHeight + _hardwareLineHeight;
-
- y += _bottomMargin;
- Size = new Size(width, y);
}
+ Resize();
+ }
- private void DrawImageWidthBorder(Graphics g, int width, int height, Image back, int t, int b, int l, int r)
+ public event EventHandler HideShowCommand;
+
+ public void SendHideShowCommand()
+ {
+ HideShowCommand?.Invoke(this, null);
+ }
+
+ private Font CreateFont(float size, FontStyle style)
+ {
+ try
{
- GraphicsUnit u = GraphicsUnit.Pixel;
-
- g.DrawImage(back, new Rectangle(0, 0, l, t), new Rectangle(0, 0, l, t), u);
- g.DrawImage(back, new Rectangle(l, 0, width - l - r, t), new Rectangle(l, 0, back.Width - l - r, t), u);
- g.DrawImage(back, new Rectangle(width - r, 0, r, t), new Rectangle(back.Width - r, 0, r, t), u);
-
- g.DrawImage(back, new Rectangle(0, t, l, height - t - b), new Rectangle(0, t, l, back.Height - t - b), u);
- g.DrawImage(back, new Rectangle(l, t, width - l - r, height - t - b), new Rectangle(l, t, back.Width - l - r, back.Height - t - b), u);
- g.DrawImage(back, new Rectangle(width - r, t, r, height - t - b), new Rectangle(back.Width - r, t, r, back.Height - t - b), u);
-
- g.DrawImage(back, new Rectangle(0, height - b, l, b), new Rectangle(0, back.Height - b, l, b), u);
- g.DrawImage(back, new Rectangle(l, height - b, width - l - r, b), new Rectangle(l, back.Height - b, back.Width - l - r, b), u);
- g.DrawImage(back, new Rectangle(width - r, height - b, r, b), new Rectangle(back.Width - r, back.Height - b, r, b), u);
+ return new Font(SystemFonts.MessageBoxFont.FontFamily, size, style);
}
-
- private void DrawBackground(Graphics g)
+ catch (ArgumentException)
{
- int w = Size.Width;
- int h = Size.Height;
+ // if the style is not supported, fall back to the original one
+ return new Font(SystemFonts.MessageBoxFont.FontFamily, size,
+ SystemFonts.MessageBoxFont.Style);
+ }
+ }
- if (w != _background.Width || h != _background.Height)
+ private void SetFontSize(float size)
+ {
+ _fontSize = size;
+ _largeFont = CreateFont(_fontSize, FontStyle.Bold);
+ _smallFont = CreateFont(_fontSize, FontStyle.Regular);
+
+ double scaledFontSize = _fontSize * _scale;
+ _iconSize = (int)Math.Round(1.5 * scaledFontSize);
+ _hardwareLineHeight = (int)Math.Round(1.66 * scaledFontSize);
+ _sensorLineHeight = (int)Math.Round(1.33 * scaledFontSize);
+ _leftMargin = LeftBorder + (int)Math.Round(0.3 * scaledFontSize);
+ _rightMargin = RightBorder + (int)Math.Round(0.3 * scaledFontSize);
+ _topMargin = TopBorder;
+ _bottomMargin = BottomBorder + (int)Math.Round(0.3 * scaledFontSize);
+ _progressWidth = (int)Math.Round(5.3 * scaledFontSize);
+
+ Resize((int)Math.Round(17.3 * scaledFontSize));
+ }
+
+ private void SetFontColor(Color color)
+ {
+ _textBrush?.Dispose();
+ _textBrush = new SolidBrush(color);
+ }
+
+ private void Resize()
+ {
+ Resize(Size.Width);
+ }
+
+ private void Resize(int width)
+ {
+ int y = _topMargin;
+
+ foreach (KeyValuePair> pair in _sensors)
+ {
+ if (_hardwareNames.Value)
{
- _background.Dispose();
- _background = new Bitmap(w, h, PixelFormat.Format32bppPArgb);
+ if (y > _topMargin)
+ y += _hardwareLineHeight - _sensorLineHeight;
+ y += _hardwareLineHeight;
+ }
+ y += pair.Value.Count * _sensorLineHeight;
+ }
- using (Graphics graphics = Graphics.FromImage(_background))
+ if (_sensors.Count == 0)
+ y += 4 * _sensorLineHeight + _hardwareLineHeight;
+
+ y += _bottomMargin;
+ Size = new Size(width, y);
+ }
+
+ private void DrawImageWidthBorder(Graphics g, int width, int height, Image back, int t, int b, int l, int r)
+ {
+ GraphicsUnit u = GraphicsUnit.Pixel;
+
+ g.DrawImage(back, new Rectangle(0, 0, l, t), new Rectangle(0, 0, l, t), u);
+ g.DrawImage(back, new Rectangle(l, 0, width - l - r, t), new Rectangle(l, 0, back.Width - l - r, t), u);
+ g.DrawImage(back, new Rectangle(width - r, 0, r, t), new Rectangle(back.Width - r, 0, r, t), u);
+
+ g.DrawImage(back, new Rectangle(0, t, l, height - t - b), new Rectangle(0, t, l, back.Height - t - b), u);
+ g.DrawImage(back, new Rectangle(l, t, width - l - r, height - t - b), new Rectangle(l, t, back.Width - l - r, back.Height - t - b), u);
+ g.DrawImage(back, new Rectangle(width - r, t, r, height - t - b), new Rectangle(back.Width - r, t, r, back.Height - t - b), u);
+
+ g.DrawImage(back, new Rectangle(0, height - b, l, b), new Rectangle(0, back.Height - b, l, b), u);
+ g.DrawImage(back, new Rectangle(l, height - b, width - l - r, b), new Rectangle(l, back.Height - b, back.Width - l - r, b), u);
+ g.DrawImage(back, new Rectangle(width - r, height - b, r, b), new Rectangle(back.Width - r, back.Height - b, r, b), u);
+ }
+
+ private void DrawBackground(Graphics g)
+ {
+ int w = Size.Width;
+ int h = Size.Height;
+
+ if (w != _background.Width || h != _background.Height)
+ {
+ _background.Dispose();
+ _background = new Bitmap(w, h, PixelFormat.Format32bppPArgb);
+
+ using (Graphics graphics = Graphics.FromImage(_background))
+ {
+ DrawImageWidthBorder(graphics, w, h, _back, TopBorder, BottomBorder,LeftBorder, RightBorder);
+
+ if (_fore != null)
+ DrawImageWidthBorder(graphics, w, h, _fore, TopBorder, BottomBorder, LeftBorder, RightBorder);
+
+ if (_image != null)
{
- DrawImageWidthBorder(graphics, w, h, _back, TopBorder, BottomBorder,LeftBorder, RightBorder);
+ int width = w - LeftBorder - RightBorder;
+ int height = h - TopBorder - BottomBorder;
+ float xRatio = width / (float)_image.Width;
+ float yRatio = height / (float)_image.Height;
+ float destWidth, destHeight;
+ float xOffset, yOffset;
- if (_fore != null)
- DrawImageWidthBorder(graphics, w, h, _fore, TopBorder, BottomBorder, LeftBorder, RightBorder);
-
- if (_image != null)
+ if (xRatio < yRatio)
{
- int width = w - LeftBorder - RightBorder;
- int height = h - TopBorder - BottomBorder;
- float xRatio = width / (float)_image.Width;
- float yRatio = height / (float)_image.Height;
- float destWidth, destHeight;
- float xOffset, yOffset;
-
- if (xRatio < yRatio)
- {
- destWidth = width;
- destHeight = _image.Height * xRatio;
- xOffset = 0;
- yOffset = 0.5f * (height - destHeight);
- }
- else
- {
- destWidth = _image.Width * yRatio;
- destHeight = height;
- xOffset = 0.5f * (width - destWidth);
- yOffset = 0;
- }
-
- graphics.DrawImage(_image, new RectangleF(LeftBorder + xOffset, TopBorder + yOffset, destWidth, destHeight));
- }
- }
- }
-
- g.DrawImageUnscaled(_background, 0, 0);
- }
-
- private void DrawProgress(Graphics g, float x, float y, float width, float height, float progress)
- {
- g.DrawImage(_barBack,
- new RectangleF(x + width * progress, y, width * (1 - progress), height),
- new RectangleF(_barBack.Width * progress, 0, (1 - progress) * _barBack.Width, _barBack.Height),
- GraphicsUnit.Pixel);
- g.DrawImage(_barFore,
- new RectangleF(x, y, width * progress, height),
- new RectangleF(0, 0, progress * _barFore.Width, _barFore.Height), GraphicsUnit.Pixel);
- }
-
- protected override void OnPaint(PaintEventArgs e)
- {
- Graphics g = e.Graphics;
- int w = Size.Width;
-
- g.Clear(Color.Transparent);
- DrawBackground(g);
-
- int x;
- int y = _topMargin;
-
- if (_sensors.Count == 0)
- {
- x = LeftBorder + 1;
- g.DrawString("Right-click on a sensor in the main window and select " +
- "\"Show in Gadget\" to show the sensor here.",
- _smallFont, _textBrush,
- new Rectangle(x, y - 1, w - RightBorder - x, 0));
- }
-
- foreach (KeyValuePair> pair in _sensors)
- {
- if (_hardwareNames.Value)
- {
- if (y > _topMargin)
- y += _hardwareLineHeight - _sensorLineHeight;
- x = LeftBorder + 1;
- g.DrawImage(HardwareTypeImage.Instance.GetImage(pair.Key.HardwareType), new Rectangle(x, y + 1, _iconSize, _iconSize));
- x += _iconSize + 1;
- g.DrawString(pair.Key.Name, _largeFont, _textBrush, new Rectangle(x, y - 1, w - RightBorder - x, 0), _stringFormat);
- y += _hardwareLineHeight;
- }
-
- foreach (ISensor sensor in pair.Value)
- {
- int remainingWidth;
-
-
- if ((sensor.SensorType != SensorType.Load &&
- sensor.SensorType != SensorType.Control &&
- sensor.SensorType != SensorType.Level) || !sensor.Value.HasValue)
- {
- string formatted;
-
- if (sensor.Value.HasValue)
- {
- string format = "";
- switch (sensor.SensorType)
- {
- case SensorType.Voltage:
- format = "{0:F3} V";
- break;
- case SensorType.Current:
- format = "{0:F3} A";
- break;
- case SensorType.Clock:
- format = "{0:F0} MHz";
- break;
- case SensorType.Frequency:
- format = "{0:F0} Hz";
- break;
- case SensorType.Temperature:
- format = "{0:F1} °C";
- break;
- case SensorType.Fan:
- format = "{0:F0} RPM";
- break;
- case SensorType.Flow:
- format = "{0:F0} L/h";
- break;
- case SensorType.Power:
- format = "{0:F1} W";
- break;
- case SensorType.Data:
- format = "{0:F1} GB";
- break;
- case SensorType.SmallData:
- format = "{0:F0} MB";
- break;
- case SensorType.Factor:
- format = "{0:F3}";
- break;
- case SensorType.TimeSpan:
- format = "{0:g}";
- break;
- case SensorType.Energy:
- format = "{0:F0} mWh";
- break;
- case SensorType.Noise:
- format = "{0:F0} dBA";
- break;
- }
-
- if (sensor.SensorType == SensorType.Temperature && _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit)
- {
- formatted = $"{UnitManager.CelsiusToFahrenheit(sensor.Value):F1} °F";
- }
- else if (sensor.SensorType == SensorType.Throughput)
- {
- string result;
- switch (sensor.Name)
- {
- case "Connection Speed":
- {
- switch (sensor.Value)
- {
- case 100000000:
- result = "100Mbps";
- break;
- case 1000000000:
- result = "1Gbps";
- break;
- default:
- {
- if (sensor.Value < 1024)
- result = $"{sensor.Value:F0} bps";
- else if (sensor.Value < 1048576)
- result = $"{sensor.Value / 1024:F1} Kbps";
- else if (sensor.Value < 1073741824)
- result = $"{sensor.Value / 1048576:F1} Mbps";
- else
- result = $"{sensor.Value / 1073741824:F1} Gbps";
- }
- break;
- }
- }
- break;
- default:
- {
- if (sensor.Value < 1048576)
- result = $"{sensor.Value / 1024:F1} KB/s";
- else
- result = $"{sensor.Value / 1048576:F1} MB/s";
- }
- break;
- }
- formatted = result;
- }
- else if (sensor.SensorType == SensorType.TimeSpan)
- {
- formatted = string.Format(format, TimeSpan.FromSeconds(sensor.Value.Value));
- }
- else
- {
- formatted = string.Format(format, sensor.Value);
- }
- }
- else
- {
- formatted = "-";
- }
-
- g.DrawString(formatted, _smallFont, _textBrush, new RectangleF(-1, y - 1, w - _rightMargin + 3, 0), _alignRightStringFormat);
-
- remainingWidth = w - (int)Math.Floor(g.MeasureString(formatted, _smallFont, w, StringFormat.GenericTypographic).Width) - _rightMargin;
+ destWidth = width;
+ destHeight = _image.Height * xRatio;
+ xOffset = 0;
+ yOffset = 0.5f * (height - destHeight);
}
else
{
- DrawProgress(g, w - _progressWidth - _rightMargin, y + 0.35f * _sensorLineHeight, _progressWidth, 0.6f * _sensorLineHeight, 0.01f * sensor.Value.Value);
- remainingWidth = w - _progressWidth - _rightMargin;
+ destWidth = _image.Width * yRatio;
+ destHeight = height;
+ xOffset = 0.5f * (width - destWidth);
+ yOffset = 0;
}
- remainingWidth -= _leftMargin + 2;
- if (remainingWidth > 0)
- {
- g.DrawString(sensor.Name, _smallFont, _textBrush, new RectangleF(_leftMargin - 1, y - 1, remainingWidth, 0), _trimStringFormat);
- }
- y += _sensorLineHeight;
+ graphics.DrawImage(_image, new RectangleF(LeftBorder + xOffset, TopBorder + yOffset, destWidth, destHeight));
}
}
}
- private class HardwareComparer : IComparer
+ g.DrawImageUnscaled(_background, 0, 0);
+ }
+
+ private void DrawProgress(Graphics g, float x, float y, float width, float height, float progress)
+ {
+ g.DrawImage(_barBack,
+ new RectangleF(x + width * progress, y, width * (1 - progress), height),
+ new RectangleF(_barBack.Width * progress, 0, (1 - progress) * _barBack.Width, _barBack.Height),
+ GraphicsUnit.Pixel);
+ g.DrawImage(_barFore,
+ new RectangleF(x, y, width * progress, height),
+ new RectangleF(0, 0, progress * _barFore.Width, _barFore.Height), GraphicsUnit.Pixel);
+ }
+
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ Graphics g = e.Graphics;
+ int w = Size.Width;
+
+ g.Clear(Color.Transparent);
+ DrawBackground(g);
+
+ int x;
+ int y = _topMargin;
+
+ if (_sensors.Count == 0)
{
- public int Compare(IHardware x, IHardware y)
+ x = LeftBorder + 1;
+ g.DrawString("Right-click on a sensor in the main window and select " +
+ "\"Show in Gadget\" to show the sensor here.",
+ _smallFont, _textBrush,
+ new Rectangle(x, y - 1, w - RightBorder - x, 0));
+ }
+
+ foreach (KeyValuePair> pair in _sensors)
+ {
+ if (_hardwareNames.Value)
{
- switch (x)
+ if (y > _topMargin)
+ y += _hardwareLineHeight - _sensorLineHeight;
+ x = LeftBorder + 1;
+ g.DrawImage(HardwareTypeImage.Instance.GetImage(pair.Key.HardwareType), new Rectangle(x, y + 1, _iconSize, _iconSize));
+ x += _iconSize + 1;
+ g.DrawString(pair.Key.Name, _largeFont, _textBrush, new Rectangle(x, y - 1, w - RightBorder - x, 0), _stringFormat);
+ y += _hardwareLineHeight;
+ }
+
+ foreach (ISensor sensor in pair.Value)
+ {
+ int remainingWidth;
+
+
+ if ((sensor.SensorType != SensorType.Load &&
+ sensor.SensorType != SensorType.Control &&
+ sensor.SensorType != SensorType.Level) || !sensor.Value.HasValue)
{
- case null when y == null:
- return 0;
- case null:
- return -1;
+ string formatted;
+
+ if (sensor.Value.HasValue)
+ {
+ string format = "";
+ switch (sensor.SensorType)
+ {
+ case SensorType.Voltage:
+ format = "{0:F3} V";
+ break;
+ case SensorType.Current:
+ format = "{0:F3} A";
+ break;
+ case SensorType.Clock:
+ format = "{0:F0} MHz";
+ break;
+ case SensorType.Frequency:
+ format = "{0:F0} Hz";
+ break;
+ case SensorType.Temperature:
+ format = "{0:F1} °C";
+ break;
+ case SensorType.Fan:
+ format = "{0:F0} RPM";
+ break;
+ case SensorType.Flow:
+ format = "{0:F0} L/h";
+ break;
+ case SensorType.Power:
+ format = "{0:F1} W";
+ break;
+ case SensorType.Data:
+ format = "{0:F1} GB";
+ break;
+ case SensorType.SmallData:
+ format = "{0:F0} MB";
+ break;
+ case SensorType.Factor:
+ format = "{0:F3}";
+ break;
+ case SensorType.TimeSpan:
+ format = "{0:g}";
+ break;
+ case SensorType.Energy:
+ format = "{0:F0} mWh";
+ break;
+ case SensorType.Noise:
+ format = "{0:F0} dBA";
+ break;
+ }
+
+ if (sensor.SensorType == SensorType.Temperature && _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit)
+ {
+ formatted = $"{UnitManager.CelsiusToFahrenheit(sensor.Value):F1} °F";
+ }
+ else if (sensor.SensorType == SensorType.Throughput)
+ {
+ string result;
+ switch (sensor.Name)
+ {
+ case "Connection Speed":
+ {
+ switch (sensor.Value)
+ {
+ case 100000000:
+ result = "100Mbps";
+ break;
+ case 1000000000:
+ result = "1Gbps";
+ break;
+ default:
+ {
+ if (sensor.Value < 1024)
+ result = $"{sensor.Value:F0} bps";
+ else if (sensor.Value < 1048576)
+ result = $"{sensor.Value / 1024:F1} Kbps";
+ else if (sensor.Value < 1073741824)
+ result = $"{sensor.Value / 1048576:F1} Mbps";
+ else
+ result = $"{sensor.Value / 1073741824:F1} Gbps";
+ }
+ break;
+ }
+ }
+ break;
+ default:
+ {
+ if (sensor.Value < 1048576)
+ result = $"{sensor.Value / 1024:F1} KB/s";
+ else
+ result = $"{sensor.Value / 1048576:F1} MB/s";
+ }
+ break;
+ }
+ formatted = result;
+ }
+ else if (sensor.SensorType == SensorType.TimeSpan)
+ {
+ formatted = string.Format(format, TimeSpan.FromSeconds(sensor.Value.Value));
+ }
+ else
+ {
+ formatted = string.Format(format, sensor.Value);
+ }
+ }
+ else
+ {
+ formatted = "-";
+ }
+
+ g.DrawString(formatted, _smallFont, _textBrush, new RectangleF(-1, y - 1, w - _rightMargin + 3, 0), _alignRightStringFormat);
+
+ remainingWidth = w - (int)Math.Floor(g.MeasureString(formatted, _smallFont, w, StringFormat.GenericTypographic).Width) - _rightMargin;
+ }
+ else
+ {
+ DrawProgress(g, w - _progressWidth - _rightMargin, y + 0.35f * _sensorLineHeight, _progressWidth, 0.6f * _sensorLineHeight, 0.01f * sensor.Value.Value);
+ remainingWidth = w - _progressWidth - _rightMargin;
}
- if (y == null)
- return 1;
-
- if (x.HardwareType != y.HardwareType)
- return x.HardwareType.CompareTo(y.HardwareType);
-
- return x.Identifier.CompareTo(y.Identifier);
+ remainingWidth -= _leftMargin + 2;
+ if (remainingWidth > 0)
+ {
+ g.DrawString(sensor.Name, _smallFont, _textBrush, new RectangleF(_leftMargin - 1, y - 1, remainingWidth, 0), _trimStringFormat);
+ }
+ y += _sensorLineHeight;
}
}
}
-}
+ private class HardwareComparer : IComparer
+ {
+ public int Compare(IHardware x, IHardware y)
+ {
+ switch (x)
+ {
+ case null when y == null:
+ return 0;
+ case null:
+ return -1;
+ }
+
+ if (y == null)
+ return 1;
+
+ if (x.HardwareType != y.HardwareType)
+ return x.HardwareType.CompareTo(y.HardwareType);
+
+ return x.Identifier.CompareTo(y.Identifier);
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/SensorNode.cs b/LibreHardwareMonitor/UI/SensorNode.cs
index 918002b..d1335fd 100644
--- a/LibreHardwareMonitor/UI/SensorNode.cs
+++ b/LibreHardwareMonitor/UI/SensorNode.cs
@@ -11,270 +11,269 @@ using System.Text;
using LibreHardwareMonitor.Hardware;
using LibreHardwareMonitor.Utilities;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class SensorNode : Node
{
- public class SensorNode : Node
+ private readonly PersistentSettings _settings;
+ private readonly UnitManager _unitManager;
+ private Color? _penColor;
+ private bool _plot;
+
+ public SensorNode(ISensor sensor, PersistentSettings settings, UnitManager unitManager)
{
- private readonly PersistentSettings _settings;
- private readonly UnitManager _unitManager;
- private Color? _penColor;
- private bool _plot;
+ Sensor = sensor;
+ _settings = settings;
+ _unitManager = unitManager;
- public SensorNode(ISensor sensor, PersistentSettings settings, UnitManager unitManager)
+ switch (sensor.SensorType)
{
- Sensor = sensor;
- _settings = settings;
- _unitManager = unitManager;
-
- switch (sensor.SensorType)
- {
- case SensorType.Voltage:
- Format = "{0:F3} V";
- break;
- case SensorType.Current:
- Format = "{0:F3} A";
- break;
- case SensorType.Clock:
- Format = "{0:F1} MHz";
- break;
- case SensorType.Load:
- Format = "{0:F1} %";
- break;
- case SensorType.Temperature:
- Format = "{0:F1} °C";
- break;
- case SensorType.Fan:
- Format = "{0:F0} RPM";
- break;
- case SensorType.Flow:
- Format = "{0:F1} L/h";
- break;
- case SensorType.Control:
- Format = "{0:F1} %";
- break;
- case SensorType.Level:
- Format = "{0:F1} %";
- break;
- case SensorType.Power:
- Format = "{0:F1} W";
- break;
- case SensorType.Data:
- Format = "{0:F1} GB";
- break;
- case SensorType.SmallData:
- Format = "{0:F1} MB";
- break;
- case SensorType.Factor:
- Format = "{0:F3}";
- break;
- case SensorType.Frequency:
- Format = "{0:F1} Hz";
- break;
- case SensorType.Throughput:
- Format = "{0:F1} B/s";
- break;
- case SensorType.TimeSpan:
- Format = "{0:g}";
- break;
- case SensorType.Energy:
- Format = "{0:F0} mWh";
- break;
- case SensorType.Noise:
- Format = "{0:F0} dBA";
- break;
- }
-
- bool hidden = settings.GetValue(new Identifier(sensor.Identifier, "hidden").ToString(), sensor.IsDefaultHidden);
- base.IsVisible = !hidden;
- Plot = settings.GetValue(new Identifier(sensor.Identifier, "plot").ToString(), false);
- string id = new Identifier(sensor.Identifier, "penColor").ToString();
-
- if (settings.Contains(id))
- PenColor = settings.GetValue(id, Color.Black);
+ case SensorType.Voltage:
+ Format = "{0:F3} V";
+ break;
+ case SensorType.Current:
+ Format = "{0:F3} A";
+ break;
+ case SensorType.Clock:
+ Format = "{0:F1} MHz";
+ break;
+ case SensorType.Load:
+ Format = "{0:F1} %";
+ break;
+ case SensorType.Temperature:
+ Format = "{0:F1} °C";
+ break;
+ case SensorType.Fan:
+ Format = "{0:F0} RPM";
+ break;
+ case SensorType.Flow:
+ Format = "{0:F1} L/h";
+ break;
+ case SensorType.Control:
+ Format = "{0:F1} %";
+ break;
+ case SensorType.Level:
+ Format = "{0:F1} %";
+ break;
+ case SensorType.Power:
+ Format = "{0:F1} W";
+ break;
+ case SensorType.Data:
+ Format = "{0:F1} GB";
+ break;
+ case SensorType.SmallData:
+ Format = "{0:F1} MB";
+ break;
+ case SensorType.Factor:
+ Format = "{0:F3}";
+ break;
+ case SensorType.Frequency:
+ Format = "{0:F1} Hz";
+ break;
+ case SensorType.Throughput:
+ Format = "{0:F1} B/s";
+ break;
+ case SensorType.TimeSpan:
+ Format = "{0:g}";
+ break;
+ case SensorType.Energy:
+ Format = "{0:F0} mWh";
+ break;
+ case SensorType.Noise:
+ Format = "{0:F0} dBA";
+ break;
}
- public event EventHandler PlotSelectionChanged;
+ bool hidden = settings.GetValue(new Identifier(sensor.Identifier, "hidden").ToString(), sensor.IsDefaultHidden);
+ base.IsVisible = !hidden;
+ Plot = settings.GetValue(new Identifier(sensor.Identifier, "plot").ToString(), false);
+ string id = new Identifier(sensor.Identifier, "penColor").ToString();
- public string Format { get; set; } = "";
+ if (settings.Contains(id))
+ PenColor = settings.GetValue(id, Color.Black);
+ }
- public override bool IsVisible
+ public event EventHandler PlotSelectionChanged;
+
+ public string Format { get; set; } = "";
+
+ public override bool IsVisible
+ {
+ get { return base.IsVisible; }
+ set
{
- get { return base.IsVisible; }
- set
- {
- base.IsVisible = value;
- _settings.SetValue(new Identifier(Sensor.Identifier, "hidden").ToString(), !value);
- }
+ base.IsVisible = value;
+ _settings.SetValue(new Identifier(Sensor.Identifier, "hidden").ToString(), !value);
}
+ }
- public string Max
+ public string Max
+ {
+ get { return ValueToString(Sensor.Max); }
+ }
+
+ public string Min
+ {
+ get { return ValueToString(Sensor.Min); }
+ }
+
+ public Color? PenColor
+ {
+ get { return _penColor; }
+ set
{
- get { return ValueToString(Sensor.Max); }
- }
+ _penColor = value;
- public string Min
- {
- get { return ValueToString(Sensor.Min); }
- }
-
- public Color? PenColor
- {
- get { return _penColor; }
- set
- {
- _penColor = value;
-
- string id = new Identifier(Sensor.Identifier, "penColor").ToString();
- if (value.HasValue)
- _settings.SetValue(id, value.Value);
- else
- _settings.Remove(id);
-
- PlotSelectionChanged?.Invoke(this, null);
- }
- }
-
- public bool Plot
- {
- get { return _plot; }
- set
- {
- _plot = value;
- _settings.SetValue(new Identifier(Sensor.Identifier, "plot").ToString(), value);
- PlotSelectionChanged?.Invoke(this, null);
- }
- }
-
- public ISensor Sensor { get; }
-
- public override string Text
- {
- get { return Sensor.Name; }
- set { Sensor.Name = value; }
- }
-
- public override string ToolTip
- {
- get
- {
- StringBuilder stringBuilder = new();
-
- if (Sensor is ICriticalSensorLimits criticalSensorLimits)
- OptionallyAppendCriticalRange(stringBuilder, criticalSensorLimits.CriticalLowLimit, criticalSensorLimits.CriticalHighLimit, "critical");
-
- if (Sensor is ISensorLimits sensorLimits)
- OptionallyAppendCriticalRange(stringBuilder, sensorLimits.LowLimit, sensorLimits.HighLimit, "normal");
-
- return stringBuilder.ToString();
- }
- }
-
- public string Value
- {
- get { return ValueToString(Sensor.Value); }
- }
-
- public string ValueToString(float? value)
- {
+ string id = new Identifier(Sensor.Identifier, "penColor").ToString();
if (value.HasValue)
+ _settings.SetValue(id, value.Value);
+ else
+ _settings.Remove(id);
+
+ PlotSelectionChanged?.Invoke(this, null);
+ }
+ }
+
+ public bool Plot
+ {
+ get { return _plot; }
+ set
+ {
+ _plot = value;
+ _settings.SetValue(new Identifier(Sensor.Identifier, "plot").ToString(), value);
+ PlotSelectionChanged?.Invoke(this, null);
+ }
+ }
+
+ public ISensor Sensor { get; }
+
+ public override string Text
+ {
+ get { return Sensor.Name; }
+ set { Sensor.Name = value; }
+ }
+
+ public override string ToolTip
+ {
+ get
+ {
+ StringBuilder stringBuilder = new();
+
+ if (Sensor is ICriticalSensorLimits criticalSensorLimits)
+ OptionallyAppendCriticalRange(stringBuilder, criticalSensorLimits.CriticalLowLimit, criticalSensorLimits.CriticalHighLimit, "critical");
+
+ if (Sensor is ISensorLimits sensorLimits)
+ OptionallyAppendCriticalRange(stringBuilder, sensorLimits.LowLimit, sensorLimits.HighLimit, "normal");
+
+ return stringBuilder.ToString();
+ }
+ }
+
+ public string Value
+ {
+ get { return ValueToString(Sensor.Value); }
+ }
+
+ public string ValueToString(float? value)
+ {
+ if (value.HasValue)
+ {
+ switch (Sensor.SensorType)
{
- switch (Sensor.SensorType)
- {
- case SensorType.Temperature when _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit:
+ case SensorType.Temperature when _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit:
{
return $"{value * 1.8 + 32:F1} °F";
}
- case SensorType.Throughput:
+ case SensorType.Throughput:
{
string result;
switch (Sensor.Name)
{
case "Connection Speed":
- {
- switch (value)
{
- case 100000000:
+ switch (value)
{
- result = "100Mbps";
- break;
- }
- case 1000000000:
- {
- result = "1Gbps";
- break;
- }
- default:
- {
- if (value < 1024)
- result = $"{value:F0} bps";
- else if (value < 1048576)
- result = $"{value / 1024:F1} Kbps";
- else if (value < 1073741824)
- result = $"{value / 1048576:F1} Mbps";
- else
- result = $"{value / 1073741824:F1} Gbps";
+ case 100000000:
+ {
+ result = "100Mbps";
+ break;
+ }
+ case 1000000000:
+ {
+ result = "1Gbps";
+ break;
+ }
+ default:
+ {
+ if (value < 1024)
+ result = $"{value:F0} bps";
+ else if (value < 1048576)
+ result = $"{value / 1024:F1} Kbps";
+ else if (value < 1073741824)
+ result = $"{value / 1048576:F1} Mbps";
+ else
+ result = $"{value / 1073741824:F1} Gbps";
+ }
+
+ break;
}
break;
}
-
- break;
- }
default:
- {
- const int _1MB = 1048576;
+ {
+ const int _1MB = 1048576;
- result = value < _1MB ? $"{value / 1024:F1} KB/s" : $"{value / _1MB:F1} MB/s";
+ result = value < _1MB ? $"{value / 1024:F1} KB/s" : $"{value / _1MB:F1} MB/s";
- break;
- }
+ break;
+ }
}
return result;
}
- case SensorType.TimeSpan:
+ case SensorType.TimeSpan:
{
return value.HasValue ? string.Format(Format, TimeSpan.FromSeconds(value.Value)) : "-";
}
- default:
+ default:
{
return string.Format(Format, value);
}
- }
- }
-
- return "-";
- }
-
- private void OptionallyAppendCriticalRange(StringBuilder str, float? min, float? max, string kind)
- {
- if (min.HasValue)
- {
- str.AppendLine(max.HasValue
- ? $"{CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(kind)} range: {ValueToString(min)} to {ValueToString(max)}."
- : $"Minimal {kind} value: {ValueToString(min)}.");
- }
- else if (max.HasValue)
- {
- str.AppendLine($"Maximal {kind} value: {ValueToString(max)}.");
}
}
- public override bool Equals(object obj)
+ return "-";
+ }
+
+ private void OptionallyAppendCriticalRange(StringBuilder str, float? min, float? max, string kind)
+ {
+ if (min.HasValue)
{
- if (obj == null)
- return false;
-
- if (!(obj is SensorNode s))
- return false;
-
-
- return (Sensor == s.Sensor);
+ str.AppendLine(max.HasValue
+ ? $"{CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(kind)} range: {ValueToString(min)} to {ValueToString(max)}."
+ : $"Minimal {kind} value: {ValueToString(min)}.");
}
-
- public override int GetHashCode()
+ else if (max.HasValue)
{
- return Sensor.GetHashCode();
+ str.AppendLine($"Maximal {kind} value: {ValueToString(max)}.");
}
}
-}
+
+ public override bool Equals(object obj)
+ {
+ if (obj == null)
+ return false;
+
+ if (!(obj is SensorNode s))
+ return false;
+
+
+ return (Sensor == s.Sensor);
+ }
+
+ public override int GetHashCode()
+ {
+ return Sensor.GetHashCode();
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/SensorNotifyIcon.cs b/LibreHardwareMonitor/UI/SensorNotifyIcon.cs
index ec4fdf2..d622a76 100644
--- a/LibreHardwareMonitor/UI/SensorNotifyIcon.cs
+++ b/LibreHardwareMonitor/UI/SensorNotifyIcon.cs
@@ -14,268 +14,267 @@ using System.Windows.Forms;
using LibreHardwareMonitor.Hardware;
using LibreHardwareMonitor.Utilities;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class SensorNotifyIcon : IDisposable
{
- public class SensorNotifyIcon : IDisposable
+ private readonly UnitManager _unitManager;
+ private readonly NotifyIconAdv _notifyIcon;
+ private readonly Bitmap _bitmap;
+ private readonly Graphics _graphics;
+ private Color _color;
+ private Color _darkColor;
+ private Brush _brush;
+ private Brush _darkBrush;
+ private readonly Pen _pen;
+ private readonly Font _font;
+ private readonly Font _smallFont;
+
+ public SensorNotifyIcon(SystemTray sensorSystemTray, ISensor sensor, PersistentSettings settings, UnitManager unitManager)
{
- private readonly UnitManager _unitManager;
- private readonly NotifyIconAdv _notifyIcon;
- private readonly Bitmap _bitmap;
- private readonly Graphics _graphics;
- private Color _color;
- private Color _darkColor;
- private Brush _brush;
- private Brush _darkBrush;
- private readonly Pen _pen;
- private readonly Font _font;
- private readonly Font _smallFont;
+ _unitManager = unitManager;
+ Sensor = sensor;
+ _notifyIcon = new NotifyIconAdv();
- public SensorNotifyIcon(SystemTray sensorSystemTray, ISensor sensor, PersistentSettings settings, UnitManager unitManager)
+ Color defaultColor = Color.White;
+ if (sensor.SensorType == SensorType.Load || sensor.SensorType == SensorType.Control || sensor.SensorType == SensorType.Level)
+ defaultColor = Color.FromArgb(0xff, 0x70, 0x8c, 0xf1);
+
+ Color = settings.GetValue(new Identifier(sensor.Identifier, "traycolor").ToString(), defaultColor);
+
+ _pen = new Pen(Color.FromArgb(96, Color.Black));
+ ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
+ ToolStripItem hideShowItem = new ToolStripMenuItem("Hide/Show");
+ hideShowItem.Click += delegate
{
- _unitManager = unitManager;
- Sensor = sensor;
- _notifyIcon = new NotifyIconAdv();
-
- Color defaultColor = Color.White;
- if (sensor.SensorType == SensorType.Load || sensor.SensorType == SensorType.Control || sensor.SensorType == SensorType.Level)
- defaultColor = Color.FromArgb(0xff, 0x70, 0x8c, 0xf1);
-
- Color = settings.GetValue(new Identifier(sensor.Identifier, "traycolor").ToString(), defaultColor);
-
- _pen = new Pen(Color.FromArgb(96, Color.Black));
- ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
- ToolStripItem hideShowItem = new ToolStripMenuItem("Hide/Show");
- hideShowItem.Click += delegate
+ sensorSystemTray.SendHideShowCommand();
+ };
+ contextMenuStrip.Items.Add(hideShowItem);
+ contextMenuStrip.Items.Add(new ToolStripSeparator());
+ ToolStripItem removeItem = new ToolStripMenuItem("Remove Sensor");
+ removeItem.Click += delegate
+ {
+ sensorSystemTray.Remove(Sensor);
+ };
+ contextMenuStrip.Items.Add(removeItem);
+ ToolStripItem colorItem = new ToolStripMenuItem("Change Color...");
+ colorItem.Click += delegate
+ {
+ ColorDialog dialog = new ColorDialog { Color = Color };
+ if (dialog.ShowDialog() == DialogResult.OK)
{
- sensorSystemTray.SendHideShowCommand();
- };
- contextMenuStrip.Items.Add(hideShowItem);
- contextMenuStrip.Items.Add(new ToolStripSeparator());
- ToolStripItem removeItem = new ToolStripMenuItem("Remove Sensor");
- removeItem.Click += delegate
- {
- sensorSystemTray.Remove(Sensor);
- };
- contextMenuStrip.Items.Add(removeItem);
- ToolStripItem colorItem = new ToolStripMenuItem("Change Color...");
- colorItem.Click += delegate
- {
- ColorDialog dialog = new ColorDialog { Color = Color };
- if (dialog.ShowDialog() == DialogResult.OK)
- {
- Color = dialog.Color;
- settings.SetValue(new Identifier(sensor.Identifier,
- "traycolor").ToString(), Color);
- }
- };
- contextMenuStrip.Items.Add(colorItem);
- contextMenuStrip.Items.Add(new ToolStripSeparator());
- ToolStripItem exitItem = new ToolStripMenuItem("Exit");
- exitItem.Click += delegate
- {
- sensorSystemTray.SendExitCommand();
- };
- contextMenuStrip.Items.Add(exitItem);
- _notifyIcon.ContextMenuStrip = contextMenuStrip;
- _notifyIcon.DoubleClick += delegate
- {
- sensorSystemTray.SendHideShowCommand();
- };
-
- // get the default dpi to create an icon with the correct size
- float dpiX, dpiY;
- using (Bitmap b = new Bitmap(1, 1, PixelFormat.Format32bppArgb))
- {
- dpiX = b.HorizontalResolution;
- dpiY = b.VerticalResolution;
+ Color = dialog.Color;
+ settings.SetValue(new Identifier(sensor.Identifier,
+ "traycolor").ToString(), Color);
}
+ };
+ contextMenuStrip.Items.Add(colorItem);
+ contextMenuStrip.Items.Add(new ToolStripSeparator());
+ ToolStripItem exitItem = new ToolStripMenuItem("Exit");
+ exitItem.Click += delegate
+ {
+ sensorSystemTray.SendExitCommand();
+ };
+ contextMenuStrip.Items.Add(exitItem);
+ _notifyIcon.ContextMenuStrip = contextMenuStrip;
+ _notifyIcon.DoubleClick += delegate
+ {
+ sensorSystemTray.SendHideShowCommand();
+ };
- // adjust the size of the icon to current dpi (default is 16x16 at 96 dpi)
- int width = (int)Math.Round(16 * dpiX / 96);
- int height = (int)Math.Round(16 * dpiY / 96);
-
- // make sure it does never get smaller than 16x16
- width = width < 16 ? 16 : width;
- height = height < 16 ? 16 : height;
-
- // adjust the font size to the icon size
- FontFamily family = SystemFonts.MessageBoxFont.FontFamily;
- float baseSize;
- switch (family.Name)
- {
- case "Segoe UI": baseSize = 12; break;
- case "Tahoma": baseSize = 11; break;
- default: baseSize = 12; break;
- }
-
- _font = new Font(family, baseSize * width / 16.0f, GraphicsUnit.Pixel);
- _smallFont = new Font(family, 0.75f * baseSize * width / 16.0f, GraphicsUnit.Pixel);
-
- _bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
- _graphics = Graphics.FromImage(_bitmap);
- if (Environment.OSVersion.Version.Major > 5)
- {
- _graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
- _graphics.SmoothingMode = SmoothingMode.HighQuality;
- }
+ // get the default dpi to create an icon with the correct size
+ float dpiX, dpiY;
+ using (Bitmap b = new Bitmap(1, 1, PixelFormat.Format32bppArgb))
+ {
+ dpiX = b.HorizontalResolution;
+ dpiY = b.VerticalResolution;
}
- public ISensor Sensor { get; }
+ // adjust the size of the icon to current dpi (default is 16x16 at 96 dpi)
+ int width = (int)Math.Round(16 * dpiX / 96);
+ int height = (int)Math.Round(16 * dpiY / 96);
- public Color Color
+ // make sure it does never get smaller than 16x16
+ width = width < 16 ? 16 : width;
+ height = height < 16 ? 16 : height;
+
+ // adjust the font size to the icon size
+ FontFamily family = SystemFonts.MessageBoxFont.FontFamily;
+ float baseSize;
+ switch (family.Name)
{
- get { return _color; }
- set
- {
- _color = value;
- _darkColor = Color.FromArgb(255, _color.R / 3, _color.G / 3, _color.B / 3);
- Brush brush = _brush;
- _brush = new SolidBrush(_color);
- brush?.Dispose();
- Brush darkBrush = _darkBrush;
- _darkBrush = new SolidBrush(_darkColor);
- darkBrush?.Dispose();
- }
+ case "Segoe UI": baseSize = 12; break;
+ case "Tahoma": baseSize = 11; break;
+ default: baseSize = 12; break;
}
- public void Dispose()
+ _font = new Font(family, baseSize * width / 16.0f, GraphicsUnit.Pixel);
+ _smallFont = new Font(family, 0.75f * baseSize * width / 16.0f, GraphicsUnit.Pixel);
+
+ _bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
+ _graphics = Graphics.FromImage(_bitmap);
+ if (Environment.OSVersion.Version.Major > 5)
{
- Icon icon = _notifyIcon.Icon;
- _notifyIcon.Icon = null;
- icon?.Destroy();
- _notifyIcon.Dispose();
-
- _brush?.Dispose();
- _darkBrush?.Dispose();
- _pen.Dispose();
- _graphics.Dispose();
- _bitmap.Dispose();
- _font.Dispose();
- _smallFont.Dispose();
- }
-
- private string GetString()
- {
- if (!Sensor.Value.HasValue)
- return "-";
-
- switch (Sensor.SensorType)
- {
- case SensorType.Temperature:
- return _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit ? $"{UnitManager.CelsiusToFahrenheit(Sensor.Value):F0}" : $"{Sensor.Value:F0}";
- case SensorType.TimeSpan:
- return $"{TimeSpan.FromSeconds(Sensor.Value.Value):g}";
- case SensorType.Clock:
- case SensorType.Fan:
- case SensorType.Flow:
- return $"{1e-3f * Sensor.Value:F1}";
- case SensorType.Voltage:
- case SensorType.Current:
- case SensorType.SmallData:
- case SensorType.Factor:
- case SensorType.Throughput:
- return $"{Sensor.Value:F1}";
- case SensorType.Control:
- case SensorType.Frequency:
- case SensorType.Level:
- case SensorType.Power:
- case SensorType.Data:
- case SensorType.Load:
- case SensorType.Energy:
- case SensorType.Noise:
- return $"{Sensor.Value:F0}";
- default:
- return "-";
- }
- }
-
- private Icon CreateTransparentIcon()
- {
- string text = GetString();
- int count = 0;
- for (int i = 0; i < text.Length; i++)
- if ((text[i] >= '0' && text[i] <= '9') || text[i] == '-')
- count++;
- bool small = count > 2;
-
- _graphics.Clear(Color.Transparent);
- Rectangle bounds = new Rectangle(Point.Empty, _bitmap.Size);
- TextRenderer.DrawText(_graphics, text, small ? _smallFont : _font, bounds, _color, Color.Transparent, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
-
- return IconFactory.Create(_bitmap);
- }
-
- private Icon CreatePercentageIcon()
- {
- try
- {
- _graphics.Clear(Color.Transparent);
- }
- catch (ArgumentException)
- {
- _graphics.Clear(Color.Black);
- }
- _graphics.FillRectangle(_darkBrush, 0.5f, -0.5f, _bitmap.Width - 2, _bitmap.Height);
- float value = Sensor.Value.GetValueOrDefault();
- float y = (float)(_bitmap.Height * 0.01f) * (100 - value);
- _graphics.FillRectangle(_brush, 0.5f, -0.5f + y, _bitmap.Width - 2, _bitmap.Height - y);
- _graphics.DrawRectangle(_pen, 1, 0, _bitmap.Width - 3, _bitmap.Height - 1);
-
- return IconFactory.Create(_bitmap);
- }
-
- public void Update()
- {
- Icon icon = _notifyIcon.Icon;
-
- switch (Sensor.SensorType)
- {
- case SensorType.Load:
- case SensorType.Control:
- case SensorType.Level:
- _notifyIcon.Icon = CreatePercentageIcon();
- break;
- default:
- _notifyIcon.Icon = CreateTransparentIcon();
- break;
- }
-
- icon?.Destroy();
-
- string format = "";
- switch (Sensor.SensorType)
- {
- case SensorType.Voltage: format = "\n{0}: {1:F2} V"; break;
- case SensorType.Current: format = "\n{0}: {1:F2} A"; break;
- case SensorType.Clock: format = "\n{0}: {1:F0} MHz"; break;
- case SensorType.Load: format = "\n{0}: {1:F1} %"; break;
- case SensorType.Temperature: format = "\n{0}: {1:F1} °C"; break;
- case SensorType.Fan: format = "\n{0}: {1:F0} RPM"; break;
- case SensorType.Flow: format = "\n{0}: {1:F0} L/h"; break;
- case SensorType.Control: format = "\n{0}: {1:F1} %"; break;
- case SensorType.Level: format = "\n{0}: {1:F1} %"; break;
- case SensorType.Power: format = "\n{0}: {1:F0} W"; break;
- case SensorType.Data: format = "\n{0}: {1:F0} GB"; break;
- case SensorType.Factor: format = "\n{0}: {1:F3} GB"; break;
- case SensorType.Energy: format = "\n{0}: {0:F0} mWh"; break;
- case SensorType.Noise: format = "\n{0}: {0:F0} dBA"; break;
- }
- string formattedValue = string.Format(format, Sensor.Name, Sensor.Value);
-
- if (Sensor.SensorType == SensorType.Temperature && _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit)
- {
- format = "\n{0}: {1:F1} °F";
- formattedValue = string.Format(format, Sensor.Name, UnitManager.CelsiusToFahrenheit(Sensor.Value));
- }
-
- string hardwareName = Sensor.Hardware.Name;
- hardwareName = hardwareName.Substring(0, Math.Min(63 - formattedValue.Length, hardwareName.Length));
- string text = hardwareName + formattedValue;
- if (text.Length > 63)
- text = null;
-
- _notifyIcon.Text = text;
- _notifyIcon.Visible = true;
+ _graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
+ _graphics.SmoothingMode = SmoothingMode.HighQuality;
}
}
-}
+
+ public ISensor Sensor { get; }
+
+ public Color Color
+ {
+ get { return _color; }
+ set
+ {
+ _color = value;
+ _darkColor = Color.FromArgb(255, _color.R / 3, _color.G / 3, _color.B / 3);
+ Brush brush = _brush;
+ _brush = new SolidBrush(_color);
+ brush?.Dispose();
+ Brush darkBrush = _darkBrush;
+ _darkBrush = new SolidBrush(_darkColor);
+ darkBrush?.Dispose();
+ }
+ }
+
+ public void Dispose()
+ {
+ Icon icon = _notifyIcon.Icon;
+ _notifyIcon.Icon = null;
+ icon?.Destroy();
+ _notifyIcon.Dispose();
+
+ _brush?.Dispose();
+ _darkBrush?.Dispose();
+ _pen.Dispose();
+ _graphics.Dispose();
+ _bitmap.Dispose();
+ _font.Dispose();
+ _smallFont.Dispose();
+ }
+
+ private string GetString()
+ {
+ if (!Sensor.Value.HasValue)
+ return "-";
+
+ switch (Sensor.SensorType)
+ {
+ case SensorType.Temperature:
+ return _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit ? $"{UnitManager.CelsiusToFahrenheit(Sensor.Value):F0}" : $"{Sensor.Value:F0}";
+ case SensorType.TimeSpan:
+ return $"{TimeSpan.FromSeconds(Sensor.Value.Value):g}";
+ case SensorType.Clock:
+ case SensorType.Fan:
+ case SensorType.Flow:
+ return $"{1e-3f * Sensor.Value:F1}";
+ case SensorType.Voltage:
+ case SensorType.Current:
+ case SensorType.SmallData:
+ case SensorType.Factor:
+ case SensorType.Throughput:
+ return $"{Sensor.Value:F1}";
+ case SensorType.Control:
+ case SensorType.Frequency:
+ case SensorType.Level:
+ case SensorType.Power:
+ case SensorType.Data:
+ case SensorType.Load:
+ case SensorType.Energy:
+ case SensorType.Noise:
+ return $"{Sensor.Value:F0}";
+ default:
+ return "-";
+ }
+ }
+
+ private Icon CreateTransparentIcon()
+ {
+ string text = GetString();
+ int count = 0;
+ for (int i = 0; i < text.Length; i++)
+ if ((text[i] >= '0' && text[i] <= '9') || text[i] == '-')
+ count++;
+ bool small = count > 2;
+
+ _graphics.Clear(Color.Transparent);
+ Rectangle bounds = new Rectangle(Point.Empty, _bitmap.Size);
+ TextRenderer.DrawText(_graphics, text, small ? _smallFont : _font, bounds, _color, Color.Transparent, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
+
+ return IconFactory.Create(_bitmap);
+ }
+
+ private Icon CreatePercentageIcon()
+ {
+ try
+ {
+ _graphics.Clear(Color.Transparent);
+ }
+ catch (ArgumentException)
+ {
+ _graphics.Clear(Color.Black);
+ }
+ _graphics.FillRectangle(_darkBrush, 0.5f, -0.5f, _bitmap.Width - 2, _bitmap.Height);
+ float value = Sensor.Value.GetValueOrDefault();
+ float y = (float)(_bitmap.Height * 0.01f) * (100 - value);
+ _graphics.FillRectangle(_brush, 0.5f, -0.5f + y, _bitmap.Width - 2, _bitmap.Height - y);
+ _graphics.DrawRectangle(_pen, 1, 0, _bitmap.Width - 3, _bitmap.Height - 1);
+
+ return IconFactory.Create(_bitmap);
+ }
+
+ public void Update()
+ {
+ Icon icon = _notifyIcon.Icon;
+
+ switch (Sensor.SensorType)
+ {
+ case SensorType.Load:
+ case SensorType.Control:
+ case SensorType.Level:
+ _notifyIcon.Icon = CreatePercentageIcon();
+ break;
+ default:
+ _notifyIcon.Icon = CreateTransparentIcon();
+ break;
+ }
+
+ icon?.Destroy();
+
+ string format = "";
+ switch (Sensor.SensorType)
+ {
+ case SensorType.Voltage: format = "\n{0}: {1:F2} V"; break;
+ case SensorType.Current: format = "\n{0}: {1:F2} A"; break;
+ case SensorType.Clock: format = "\n{0}: {1:F0} MHz"; break;
+ case SensorType.Load: format = "\n{0}: {1:F1} %"; break;
+ case SensorType.Temperature: format = "\n{0}: {1:F1} °C"; break;
+ case SensorType.Fan: format = "\n{0}: {1:F0} RPM"; break;
+ case SensorType.Flow: format = "\n{0}: {1:F0} L/h"; break;
+ case SensorType.Control: format = "\n{0}: {1:F1} %"; break;
+ case SensorType.Level: format = "\n{0}: {1:F1} %"; break;
+ case SensorType.Power: format = "\n{0}: {1:F0} W"; break;
+ case SensorType.Data: format = "\n{0}: {1:F0} GB"; break;
+ case SensorType.Factor: format = "\n{0}: {1:F3} GB"; break;
+ case SensorType.Energy: format = "\n{0}: {0:F0} mWh"; break;
+ case SensorType.Noise: format = "\n{0}: {0:F0} dBA"; break;
+ }
+ string formattedValue = string.Format(format, Sensor.Name, Sensor.Value);
+
+ if (Sensor.SensorType == SensorType.Temperature && _unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit)
+ {
+ format = "\n{0}: {1:F1} °F";
+ formattedValue = string.Format(format, Sensor.Name, UnitManager.CelsiusToFahrenheit(Sensor.Value));
+ }
+
+ string hardwareName = Sensor.Hardware.Name;
+ hardwareName = hardwareName.Substring(0, Math.Min(63 - formattedValue.Length, hardwareName.Length));
+ string text = hardwareName + formattedValue;
+ if (text.Length > 63)
+ text = null;
+
+ _notifyIcon.Text = text;
+ _notifyIcon.Visible = true;
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/ShowDesktop.cs b/LibreHardwareMonitor/UI/ShowDesktop.cs
index 8ee34c0..97d1dbf 100644
--- a/LibreHardwareMonitor/UI/ShowDesktop.cs
+++ b/LibreHardwareMonitor/UI/ShowDesktop.cs
@@ -8,151 +8,150 @@ using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class ShowDesktop : IDisposable
{
- public class ShowDesktop : IDisposable
+ private readonly NativeWindow _referenceWindow;
+ private readonly string _referenceWindowCaption = "LibreHardwareMonitorShowDesktopReferenceWindow";
+ private readonly System.Threading.Timer _timer;
+ private bool _showDesktop;
+
+ ///
+ /// Prevents a default instance of the class from being created.
+ ///
+ private ShowDesktop()
{
- private readonly NativeWindow _referenceWindow;
- private readonly string _referenceWindowCaption = "LibreHardwareMonitorShowDesktopReferenceWindow";
- private readonly System.Threading.Timer _timer;
- private bool _showDesktop;
+ // Create a reference window to detect show desktop
+ _referenceWindow = new NativeWindow();
- ///
- /// Prevents a default instance of the class from being created.
- ///
- private ShowDesktop()
+ CreateParams cp = new CreateParams { ExStyle = GadgetWindow.WS_EX_TOOLWINDOW, Caption = _referenceWindowCaption };
+ _referenceWindow.CreateHandle(cp);
+ NativeMethods.SetWindowPos(_referenceWindow.Handle,
+ GadgetWindow.HWND_BOTTOM,
+ 0,
+ 0,
+ 0,
+ 0,
+ GadgetWindow.SWP_NOMOVE |
+ GadgetWindow.SWP_NOSIZE |
+ GadgetWindow.SWP_NOACTIVATE |
+ GadgetWindow.SWP_NOSENDCHANGING);
+
+ // start a repeated timer to detect "Show Desktop" events
+ _timer = new System.Threading.Timer(OnTimer, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
+ }
+
+ public delegate void ShowDesktopChangedEventHandler(bool showDesktop);
+
+ private event ShowDesktopChangedEventHandler ShowDesktopChangedEvent;
+
+ // notify when the "show desktop" mode is changed
+ public event ShowDesktopChangedEventHandler ShowDesktopChanged
+ {
+ add
{
- // Create a reference window to detect show desktop
- _referenceWindow = new NativeWindow();
+ // start the monitor timer when someone is listening
+ if (ShowDesktopChangedEvent == null)
+ StartTimer();
- CreateParams cp = new CreateParams { ExStyle = GadgetWindow.WS_EX_TOOLWINDOW, Caption = _referenceWindowCaption };
- _referenceWindow.CreateHandle(cp);
- NativeMethods.SetWindowPos(_referenceWindow.Handle,
- GadgetWindow.HWND_BOTTOM,
- 0,
- 0,
- 0,
- 0,
- GadgetWindow.SWP_NOMOVE |
- GadgetWindow.SWP_NOSIZE |
- GadgetWindow.SWP_NOACTIVATE |
- GadgetWindow.SWP_NOSENDCHANGING);
-
- // start a repeated timer to detect "Show Desktop" events
- _timer = new System.Threading.Timer(OnTimer, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
+ ShowDesktopChangedEvent += value;
}
-
- public delegate void ShowDesktopChangedEventHandler(bool showDesktop);
-
- private event ShowDesktopChangedEventHandler ShowDesktopChangedEvent;
-
- // notify when the "show desktop" mode is changed
- public event ShowDesktopChangedEventHandler ShowDesktopChanged
+ remove
{
- add
- {
- // start the monitor timer when someone is listening
- if (ShowDesktopChangedEvent == null)
- StartTimer();
-
- ShowDesktopChangedEvent += value;
- }
- remove
- {
- ShowDesktopChangedEvent -= value;
- // stop the monitor timer if nobody is interested
- if (ShowDesktopChangedEvent == null)
- StopTimer();
- }
- }
-
- public static ShowDesktop Instance { get; } = new ShowDesktop();
-
- ///
- public void Dispose()
- {
- _timer?.Dispose();
- _referenceWindow.ReleaseHandle();
- }
-
- private void StartTimer()
- {
- _timer.Change(0, 200);
- }
-
- private void StopTimer()
- {
- _timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
- }
-
- // the desktop worker window (if available) can hide the reference window
- private IntPtr GetDesktopWorkerWindow()
- {
- IntPtr shellWindow = NativeMethods.GetShellWindow();
- if (shellWindow == IntPtr.Zero)
- return IntPtr.Zero;
-
-
- NativeMethods.GetWindowThreadProcessId(shellWindow, out int shellId);
-
- IntPtr workerWindow = IntPtr.Zero;
- while ((workerWindow = NativeMethods.FindWindowEx(IntPtr.Zero, workerWindow, "WorkerW", null)) != IntPtr.Zero)
- {
- NativeMethods.GetWindowThreadProcessId(workerWindow, out int workerId);
- if (workerId == shellId)
- {
- IntPtr window = NativeMethods.FindWindowEx(workerWindow, IntPtr.Zero, "SHELLDLL_DefView", null);
- if (window != IntPtr.Zero)
- {
- IntPtr desktopWindow = NativeMethods.FindWindowEx(window, IntPtr.Zero, "SysListView32", null);
- if (desktopWindow != IntPtr.Zero)
- return workerWindow;
- }
- }
- }
-
- return IntPtr.Zero;
- }
-
- private void OnTimer(object state)
- {
- bool showDesktopDetected;
-
- IntPtr workerWindow = GetDesktopWorkerWindow();
- if (workerWindow != IntPtr.Zero)
- {
- // search if the reference window is behind the worker window
- IntPtr reference = NativeMethods.FindWindowEx(IntPtr.Zero, workerWindow, null, _referenceWindowCaption);
- showDesktopDetected = reference != IntPtr.Zero;
- }
- else
- {
- // if there is no worker window, then nothing can hide the reference
- showDesktopDetected = false;
- }
-
- if (_showDesktop != showDesktopDetected)
- {
- _showDesktop = showDesktopDetected;
- ShowDesktopChangedEvent?.Invoke(_showDesktop);
- }
- }
-
- private static class NativeMethods
- {
- private const string USER = "user32.dll";
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- public static extern IntPtr GetShellWindow();
-
- [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
- public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
+ ShowDesktopChangedEvent -= value;
+ // stop the monitor timer if nobody is interested
+ if (ShowDesktopChangedEvent == null)
+ StopTimer();
}
}
-}
+
+ public static ShowDesktop Instance { get; } = new ShowDesktop();
+
+ ///
+ public void Dispose()
+ {
+ _timer?.Dispose();
+ _referenceWindow.ReleaseHandle();
+ }
+
+ private void StartTimer()
+ {
+ _timer.Change(0, 200);
+ }
+
+ private void StopTimer()
+ {
+ _timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
+ }
+
+ // the desktop worker window (if available) can hide the reference window
+ private IntPtr GetDesktopWorkerWindow()
+ {
+ IntPtr shellWindow = NativeMethods.GetShellWindow();
+ if (shellWindow == IntPtr.Zero)
+ return IntPtr.Zero;
+
+
+ NativeMethods.GetWindowThreadProcessId(shellWindow, out int shellId);
+
+ IntPtr workerWindow = IntPtr.Zero;
+ while ((workerWindow = NativeMethods.FindWindowEx(IntPtr.Zero, workerWindow, "WorkerW", null)) != IntPtr.Zero)
+ {
+ NativeMethods.GetWindowThreadProcessId(workerWindow, out int workerId);
+ if (workerId == shellId)
+ {
+ IntPtr window = NativeMethods.FindWindowEx(workerWindow, IntPtr.Zero, "SHELLDLL_DefView", null);
+ if (window != IntPtr.Zero)
+ {
+ IntPtr desktopWindow = NativeMethods.FindWindowEx(window, IntPtr.Zero, "SysListView32", null);
+ if (desktopWindow != IntPtr.Zero)
+ return workerWindow;
+ }
+ }
+ }
+
+ return IntPtr.Zero;
+ }
+
+ private void OnTimer(object state)
+ {
+ bool showDesktopDetected;
+
+ IntPtr workerWindow = GetDesktopWorkerWindow();
+ if (workerWindow != IntPtr.Zero)
+ {
+ // search if the reference window is behind the worker window
+ IntPtr reference = NativeMethods.FindWindowEx(IntPtr.Zero, workerWindow, null, _referenceWindowCaption);
+ showDesktopDetected = reference != IntPtr.Zero;
+ }
+ else
+ {
+ // if there is no worker window, then nothing can hide the reference
+ showDesktopDetected = false;
+ }
+
+ if (_showDesktop != showDesktopDetected)
+ {
+ _showDesktop = showDesktopDetected;
+ ShowDesktopChangedEvent?.Invoke(_showDesktop);
+ }
+ }
+
+ private static class NativeMethods
+ {
+ private const string USER = "user32.dll";
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ public static extern IntPtr GetShellWindow();
+
+ [DllImport(USER, CallingConvention = CallingConvention.Winapi)]
+ public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/SplitContainerAdv.cs b/LibreHardwareMonitor/UI/SplitContainerAdv.cs
index d6c592d..4d92e28 100644
--- a/LibreHardwareMonitor/UI/SplitContainerAdv.cs
+++ b/LibreHardwareMonitor/UI/SplitContainerAdv.cs
@@ -8,132 +8,131 @@ using System;
using System.Drawing;
using System.Windows.Forms;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class SplitContainerAdv : SplitContainer
{
- public class SplitContainerAdv : SplitContainer
+ private int _delta;
+ private Border3DStyle _border3DStyle = Border3DStyle.Raised;
+ private Color _bgColor = SystemColors.Control;
+
+ public SplitContainerAdv()
{
- private int _delta;
- private Border3DStyle _border3DStyle = Border3DStyle.Raised;
- private Color _bgColor = SystemColors.Control;
+ SetStyle(ControlStyles.ResizeRedraw, true);
+ SetStyle(ControlStyles.AllPaintingInWmPaint, true);
+ SetStyle(ControlStyles.UserPaint, true);
+ SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
+ SetStyle(ControlStyles.ContainerControl, true);
+ UpdateStyles();
+ }
- public SplitContainerAdv()
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ base.OnPaint(e);
+ Graphics g = e.Graphics;
+ Rectangle r = SplitterRectangle;
+
+ using (SolidBrush brush = new SolidBrush(_bgColor))
+ g.FillRectangle(brush, r);
+
+ ControlPaint.DrawBorder3D(g, r, _border3DStyle);
+ }
+
+ protected override void OnKeyDown(KeyEventArgs e)
+ {
+ if (!IsSplitterFixed)
{
- SetStyle(ControlStyles.ResizeRedraw, true);
- SetStyle(ControlStyles.AllPaintingInWmPaint, true);
- SetStyle(ControlStyles.UserPaint, true);
- SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
- SetStyle(ControlStyles.ContainerControl, true);
- UpdateStyles();
- }
-
- protected override void OnPaint(PaintEventArgs e)
- {
- base.OnPaint(e);
- Graphics g = e.Graphics;
- Rectangle r = SplitterRectangle;
-
- using (SolidBrush brush = new SolidBrush(_bgColor))
- g.FillRectangle(brush, r);
-
- ControlPaint.DrawBorder3D(g, r, _border3DStyle);
- }
-
- protected override void OnKeyDown(KeyEventArgs e)
- {
- if (!IsSplitterFixed)
+ switch (e.KeyData)
{
- switch (e.KeyData)
+ case Keys.Right:
+ case Keys.Down:
+ SplitterDistance += SplitterIncrement;
+ break;
+ case Keys.Left:
+ case Keys.Up:
+ SplitterDistance -= SplitterIncrement;
+ break;
+ }
+
+ Invalidate();
+ }
+ }
+
+ protected override void OnMouseDown(MouseEventArgs e)
+ {
+ if (Orientation == Orientation.Vertical)
+ {
+ _delta = SplitterDistance - e.X;
+ Cursor.Current = Cursors.VSplit;
+ }
+ else
+ {
+ _delta = SplitterDistance - e.Y;
+ Cursor.Current = Cursors.HSplit;
+ }
+ IsSplitterFixed = true;
+ }
+
+ protected override void OnMouseMove(MouseEventArgs e)
+ {
+ if (IsSplitterFixed)
+ {
+ if (e.Button == MouseButtons.Left)
+ {
+ if (Orientation == Orientation.Vertical)
{
- case Keys.Right:
- case Keys.Down:
- SplitterDistance += SplitterIncrement;
- break;
- case Keys.Left:
- case Keys.Up:
- SplitterDistance -= SplitterIncrement;
- break;
- }
-
- Invalidate();
- }
- }
-
- protected override void OnMouseDown(MouseEventArgs e)
- {
- if (Orientation == Orientation.Vertical)
- {
- _delta = SplitterDistance - e.X;
- Cursor.Current = Cursors.VSplit;
- }
- else
- {
- _delta = SplitterDistance - e.Y;
- Cursor.Current = Cursors.HSplit;
- }
- IsSplitterFixed = true;
- }
-
- protected override void OnMouseMove(MouseEventArgs e)
- {
- if (IsSplitterFixed)
- {
- if (e.Button == MouseButtons.Left)
- {
- if (Orientation == Orientation.Vertical)
- {
- if (e.X > 0 && e.X < Width)
- SplitterDistance = e.X + _delta < 0 ? 0 : e.X + _delta;
- }
- else
- {
- if (e.Y > 0 && e.Y < Height)
- SplitterDistance = e.Y + _delta < 0 ? 0 : e.Y + _delta;
- }
+ if (e.X > 0 && e.X < Width)
+ SplitterDistance = e.X + _delta < 0 ? 0 : e.X + _delta;
}
else
{
- IsSplitterFixed = false;
+ if (e.Y > 0 && e.Y < Height)
+ SplitterDistance = e.Y + _delta < 0 ? 0 : e.Y + _delta;
}
- Invalidate();
}
else
{
- if (SplitterRectangle.Contains(e.Location))
- Cursor = Orientation == Orientation.Vertical ? Cursors.VSplit : Cursors.HSplit;
+ IsSplitterFixed = false;
}
+ Invalidate();
}
-
- protected override void OnMouseLeave(EventArgs e)
+ else
{
- base.OnMouseLeave(e);
- Cursor = Cursors.Default;
- }
-
- protected override void OnMouseUp(MouseEventArgs e)
- {
- _delta = 0;
- IsSplitterFixed = false;
- Cursor.Current = Cursors.Default;
- }
-
- public Border3DStyle Border3DStyle
- {
- get { return _border3DStyle; }
- set
- {
- _border3DStyle = value;
- Invalidate(false);
- }
- }
-
- public Color Color
- {
- get { return _bgColor; }
- set
- {
- _bgColor = value;
- Invalidate(false);
- }
+ if (SplitterRectangle.Contains(e.Location))
+ Cursor = Orientation == Orientation.Vertical ? Cursors.VSplit : Cursors.HSplit;
}
}
-}
+
+ protected override void OnMouseLeave(EventArgs e)
+ {
+ base.OnMouseLeave(e);
+ Cursor = Cursors.Default;
+ }
+
+ protected override void OnMouseUp(MouseEventArgs e)
+ {
+ _delta = 0;
+ IsSplitterFixed = false;
+ Cursor.Current = Cursors.Default;
+ }
+
+ public Border3DStyle Border3DStyle
+ {
+ get { return _border3DStyle; }
+ set
+ {
+ _border3DStyle = value;
+ Invalidate(false);
+ }
+ }
+
+ public Color Color
+ {
+ get { return _bgColor; }
+ set
+ {
+ _bgColor = value;
+ Invalidate(false);
+ }
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/StartupManager.cs b/LibreHardwareMonitor/UI/StartupManager.cs
index bf5e4fa..10a8a1d 100644
--- a/LibreHardwareMonitor/UI/StartupManager.cs
+++ b/LibreHardwareMonitor/UI/StartupManager.cs
@@ -14,168 +14,167 @@ using Microsoft.Win32;
using Microsoft.Win32.TaskScheduler;
using Action = Microsoft.Win32.TaskScheduler.Action;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class StartupManager
{
- public class StartupManager
+ private const string RegistryPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
+ private bool _startup;
+
+ public StartupManager()
{
- private const string RegistryPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
- private bool _startup;
-
- public StartupManager()
+ if (Environment.OSVersion.Platform >= PlatformID.Unix)
{
- if (Environment.OSVersion.Platform >= PlatformID.Unix)
- {
- IsAvailable = false;
- return;
- }
+ IsAvailable = false;
+ return;
+ }
- if (IsAdministrator() && TaskService.Instance.Connected)
- {
- IsAvailable = true;
+ if (IsAdministrator() && TaskService.Instance.Connected)
+ {
+ IsAvailable = true;
- Task task = GetTask();
- if (task != null)
+ Task task = GetTask();
+ if (task != null)
+ {
+ foreach (Action action in task.Definition.Actions)
{
- foreach (Action action in task.Definition.Actions)
+ if (action.ActionType == TaskActionType.Execute && action is ExecAction execAction)
{
- if (action.ActionType == TaskActionType.Execute && action is ExecAction execAction)
- {
- if (execAction.Path.Equals(Application.ExecutablePath, StringComparison.OrdinalIgnoreCase))
- _startup = true;
- }
+ if (execAction.Path.Equals(Application.ExecutablePath, StringComparison.OrdinalIgnoreCase))
+ _startup = true;
}
}
}
- else
- {
- try
- {
- using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(RegistryPath))
- {
- string value = (string)registryKey?.GetValue(nameof(LibreHardwareMonitor));
-
- if (value != null)
- _startup = value == Application.ExecutablePath;
- }
-
- IsAvailable = true;
- }
- catch (SecurityException)
- {
- IsAvailable = false;
- }
- }
}
-
- public bool IsAvailable { get; }
-
- public bool Startup
+ else
{
- get { return _startup; }
- set
+ try
{
- if (_startup != value)
+ using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(RegistryPath))
{
- if (IsAvailable)
+ string value = (string)registryKey?.GetValue(nameof(LibreHardwareMonitor));
+
+ if (value != null)
+ _startup = value == Application.ExecutablePath;
+ }
+
+ IsAvailable = true;
+ }
+ catch (SecurityException)
+ {
+ IsAvailable = false;
+ }
+ }
+ }
+
+ public bool IsAvailable { get; }
+
+ public bool Startup
+ {
+ get { return _startup; }
+ set
+ {
+ if (_startup != value)
+ {
+ if (IsAvailable)
+ {
+ if (TaskService.Instance.Connected)
{
- if (TaskService.Instance.Connected)
- {
- if (value)
- CreateTask();
- else
- DeleteTask();
-
- _startup = value;
- }
+ if (value)
+ CreateTask();
else
- {
- try
- {
- if (value)
- CreateRegistryKey();
- else
- DeleteRegistryKey();
+ DeleteTask();
- _startup = value;
- }
- catch (UnauthorizedAccessException)
- {
- throw new InvalidOperationException();
- }
- }
+ _startup = value;
}
else
{
- throw new InvalidOperationException();
+ try
+ {
+ if (value)
+ CreateRegistryKey();
+ else
+ DeleteRegistryKey();
+
+ _startup = value;
+ }
+ catch (UnauthorizedAccessException)
+ {
+ throw new InvalidOperationException();
+ }
}
}
+ else
+ {
+ throw new InvalidOperationException();
+ }
}
}
+ }
- private static bool IsAdministrator()
+ private static bool IsAdministrator()
+ {
+ try
{
- try
- {
- WindowsIdentity identity = WindowsIdentity.GetCurrent();
- WindowsPrincipal principal = new WindowsPrincipal(identity);
+ WindowsIdentity identity = WindowsIdentity.GetCurrent();
+ WindowsPrincipal principal = new WindowsPrincipal(identity);
- return principal.IsInRole(WindowsBuiltInRole.Administrator);
- }
- catch
- {
- return false;
- }
+ return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
-
- private static Task GetTask()
+ catch
{
- try
- {
- return TaskService.Instance.AllTasks.FirstOrDefault(x => x.Name.Equals(nameof(LibreHardwareMonitor), StringComparison.OrdinalIgnoreCase));
- }
- catch
- {
- return null;
- }
- }
-
- private void CreateTask()
- {
- TaskDefinition taskDefinition = TaskService.Instance.NewTask();
- taskDefinition.RegistrationInfo.Description = "Starts LibreHardwareMonitor on Windows startup.";
-
- taskDefinition.Triggers.Add(new LogonTrigger());
-
- taskDefinition.Settings.StartWhenAvailable = true;
- taskDefinition.Settings.DisallowStartIfOnBatteries = false;
- taskDefinition.Settings.StopIfGoingOnBatteries = false;
- taskDefinition.Settings.ExecutionTimeLimit = TimeSpan.Zero;
- taskDefinition.Settings.AllowHardTerminate = false;
-
- taskDefinition.Principal.RunLevel = TaskRunLevel.Highest;
- taskDefinition.Principal.LogonType = TaskLogonType.InteractiveToken;
-
- taskDefinition.Actions.Add(new ExecAction(Application.ExecutablePath, "", Path.GetDirectoryName(Application.ExecutablePath)));
-
- TaskService.Instance.RootFolder.RegisterTaskDefinition(nameof(LibreHardwareMonitor), taskDefinition);
- }
-
- private static void DeleteTask()
- {
- Task task = GetTask();
- task?.Folder.DeleteTask(task.Name, false);
- }
-
- private static void CreateRegistryKey()
- {
- RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(RegistryPath);
- registryKey?.SetValue(nameof(LibreHardwareMonitor), Application.ExecutablePath);
- }
-
- private static void DeleteRegistryKey()
- {
- RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(RegistryPath);
- registryKey?.DeleteValue(nameof(LibreHardwareMonitor));
+ return false;
}
}
-}
+
+ private static Task GetTask()
+ {
+ try
+ {
+ return TaskService.Instance.AllTasks.FirstOrDefault(x => x.Name.Equals(nameof(LibreHardwareMonitor), StringComparison.OrdinalIgnoreCase));
+ }
+ catch
+ {
+ return null;
+ }
+ }
+
+ private void CreateTask()
+ {
+ TaskDefinition taskDefinition = TaskService.Instance.NewTask();
+ taskDefinition.RegistrationInfo.Description = "Starts LibreHardwareMonitor on Windows startup.";
+
+ taskDefinition.Triggers.Add(new LogonTrigger());
+
+ taskDefinition.Settings.StartWhenAvailable = true;
+ taskDefinition.Settings.DisallowStartIfOnBatteries = false;
+ taskDefinition.Settings.StopIfGoingOnBatteries = false;
+ taskDefinition.Settings.ExecutionTimeLimit = TimeSpan.Zero;
+ taskDefinition.Settings.AllowHardTerminate = false;
+
+ taskDefinition.Principal.RunLevel = TaskRunLevel.Highest;
+ taskDefinition.Principal.LogonType = TaskLogonType.InteractiveToken;
+
+ taskDefinition.Actions.Add(new ExecAction(Application.ExecutablePath, "", Path.GetDirectoryName(Application.ExecutablePath)));
+
+ TaskService.Instance.RootFolder.RegisterTaskDefinition(nameof(LibreHardwareMonitor), taskDefinition);
+ }
+
+ private static void DeleteTask()
+ {
+ Task task = GetTask();
+ task?.Folder.DeleteTask(task.Name, false);
+ }
+
+ private static void CreateRegistryKey()
+ {
+ RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(RegistryPath);
+ registryKey?.SetValue(nameof(LibreHardwareMonitor), Application.ExecutablePath);
+ }
+
+ private static void DeleteRegistryKey()
+ {
+ RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(RegistryPath);
+ registryKey?.DeleteValue(nameof(LibreHardwareMonitor));
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/SystemTray.cs b/LibreHardwareMonitor/UI/SystemTray.cs
index 75fb0ff..048d2df 100644
--- a/LibreHardwareMonitor/UI/SystemTray.cs
+++ b/LibreHardwareMonitor/UI/SystemTray.cs
@@ -10,177 +10,176 @@ using System.Windows.Forms;
using LibreHardwareMonitor.Hardware;
using LibreHardwareMonitor.Utilities;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class SystemTray : IDisposable
{
- public class SystemTray : IDisposable
+ private IComputer _computer;
+ private readonly PersistentSettings _settings;
+ private readonly UnitManager _unitManager;
+ private readonly List _sensorList = new List();
+ private bool _mainIconEnabled;
+ private readonly NotifyIconAdv _mainIcon;
+
+ public SystemTray(IComputer computer, PersistentSettings settings, UnitManager unitManager)
{
- private IComputer _computer;
- private readonly PersistentSettings _settings;
- private readonly UnitManager _unitManager;
- private readonly List _sensorList = new List();
- private bool _mainIconEnabled;
- private readonly NotifyIconAdv _mainIcon;
+ _computer = computer;
+ _settings = settings;
+ _unitManager = unitManager;
+ computer.HardwareAdded += HardwareAdded;
+ computer.HardwareRemoved += HardwareRemoved;
- public SystemTray(IComputer computer, PersistentSettings settings, UnitManager unitManager)
+ _mainIcon = new NotifyIconAdv();
+
+ ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
+ ToolStripItem hideShowItem = new ToolStripMenuItem("Hide/Show");
+ hideShowItem.Click += delegate
{
- _computer = computer;
- _settings = settings;
- _unitManager = unitManager;
- computer.HardwareAdded += HardwareAdded;
- computer.HardwareRemoved += HardwareRemoved;
+ SendHideShowCommand();
+ };
+ contextMenuStrip.Items.Add(hideShowItem);
+ contextMenuStrip.Items.Add(new ToolStripSeparator());
+ ToolStripItem exitItem = new ToolStripMenuItem("Exit");
+ exitItem.Click += delegate
+ {
+ SendExitCommand();
+ };
+ contextMenuStrip.Items.Add(exitItem);
+ _mainIcon.ContextMenuStrip = contextMenuStrip;
+ _mainIcon.DoubleClick += delegate
+ {
+ SendHideShowCommand();
+ };
+ _mainIcon.Icon = EmbeddedResources.GetIcon("smallicon.ico");
+ _mainIcon.Text = "Libre Hardware Monitor";
+ }
- _mainIcon = new NotifyIconAdv();
+ private void HardwareRemoved(IHardware hardware)
+ {
+ hardware.SensorAdded -= SensorAdded;
+ hardware.SensorRemoved -= SensorRemoved;
- ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
- ToolStripItem hideShowItem = new ToolStripMenuItem("Hide/Show");
- hideShowItem.Click += delegate
- {
- SendHideShowCommand();
- };
- contextMenuStrip.Items.Add(hideShowItem);
- contextMenuStrip.Items.Add(new ToolStripSeparator());
- ToolStripItem exitItem = new ToolStripMenuItem("Exit");
- exitItem.Click += delegate
- {
- SendExitCommand();
- };
- contextMenuStrip.Items.Add(exitItem);
- _mainIcon.ContextMenuStrip = contextMenuStrip;
- _mainIcon.DoubleClick += delegate
- {
- SendHideShowCommand();
- };
- _mainIcon.Icon = EmbeddedResources.GetIcon("smallicon.ico");
- _mainIcon.Text = "Libre Hardware Monitor";
+ foreach (ISensor sensor in hardware.Sensors)
+ SensorRemoved(sensor);
+
+ foreach (IHardware subHardware in hardware.SubHardware)
+ HardwareRemoved(subHardware);
+ }
+
+ private void HardwareAdded(IHardware hardware)
+ {
+ foreach (ISensor sensor in hardware.Sensors)
+ SensorAdded(sensor);
+
+ hardware.SensorAdded += SensorAdded;
+ hardware.SensorRemoved += SensorRemoved;
+
+ foreach (IHardware subHardware in hardware.SubHardware)
+ HardwareAdded(subHardware);
+ }
+
+ private void SensorAdded(ISensor sensor)
+ {
+ if (_settings.GetValue(new Identifier(sensor.Identifier, "tray").ToString(), false))
+ Add(sensor, false);
+ }
+
+ private void SensorRemoved(ISensor sensor)
+ {
+ if (Contains(sensor))
+ Remove(sensor, false);
+ }
+
+ public void Dispose()
+ {
+ foreach (SensorNotifyIcon icon in _sensorList)
+ icon.Dispose();
+ _mainIcon.Dispose();
+ }
+
+ public void Redraw()
+ {
+ foreach (SensorNotifyIcon icon in _sensorList)
+ icon.Update();
+ }
+
+ public bool Contains(ISensor sensor)
+ {
+ foreach (SensorNotifyIcon icon in _sensorList)
+ if (icon.Sensor == sensor)
+ return true;
+ return false;
+ }
+
+ public void Add(ISensor sensor, bool balloonTip)
+ {
+ if (Contains(sensor))
+ return;
+
+
+ _sensorList.Add(new SensorNotifyIcon(this, sensor, _settings, _unitManager));
+ UpdateMainIconVisibility();
+ _settings.SetValue(new Identifier(sensor.Identifier, "tray").ToString(), true);
+ }
+
+ public void Remove(ISensor sensor)
+ {
+ Remove(sensor, true);
+ }
+
+ private void Remove(ISensor sensor, bool deleteConfig)
+ {
+ if (deleteConfig)
+ {
+ _settings.Remove(new Identifier(sensor.Identifier, "tray").ToString());
+ _settings.Remove(new Identifier(sensor.Identifier, "traycolor").ToString());
}
-
- private void HardwareRemoved(IHardware hardware)
+ SensorNotifyIcon instance = null;
+ foreach (SensorNotifyIcon icon in _sensorList)
{
- hardware.SensorAdded -= SensorAdded;
- hardware.SensorRemoved -= SensorRemoved;
-
- foreach (ISensor sensor in hardware.Sensors)
- SensorRemoved(sensor);
-
- foreach (IHardware subHardware in hardware.SubHardware)
- HardwareRemoved(subHardware);
+ if (icon.Sensor == sensor)
+ instance = icon;
}
-
- private void HardwareAdded(IHardware hardware)
+ if (instance != null)
{
- foreach (ISensor sensor in hardware.Sensors)
- SensorAdded(sensor);
-
- hardware.SensorAdded += SensorAdded;
- hardware.SensorRemoved += SensorRemoved;
-
- foreach (IHardware subHardware in hardware.SubHardware)
- HardwareAdded(subHardware);
- }
-
- private void SensorAdded(ISensor sensor)
- {
- if (_settings.GetValue(new Identifier(sensor.Identifier, "tray").ToString(), false))
- Add(sensor, false);
- }
-
- private void SensorRemoved(ISensor sensor)
- {
- if (Contains(sensor))
- Remove(sensor, false);
- }
-
- public void Dispose()
- {
- foreach (SensorNotifyIcon icon in _sensorList)
- icon.Dispose();
- _mainIcon.Dispose();
- }
-
- public void Redraw()
- {
- foreach (SensorNotifyIcon icon in _sensorList)
- icon.Update();
- }
-
- public bool Contains(ISensor sensor)
- {
- foreach (SensorNotifyIcon icon in _sensorList)
- if (icon.Sensor == sensor)
- return true;
- return false;
- }
-
- public void Add(ISensor sensor, bool balloonTip)
- {
- if (Contains(sensor))
- return;
-
-
- _sensorList.Add(new SensorNotifyIcon(this, sensor, _settings, _unitManager));
+ _sensorList.Remove(instance);
UpdateMainIconVisibility();
- _settings.SetValue(new Identifier(sensor.Identifier, "tray").ToString(), true);
+ instance.Dispose();
}
+ }
- public void Remove(ISensor sensor)
- {
- Remove(sensor, true);
- }
+ public event EventHandler HideShowCommand;
- private void Remove(ISensor sensor, bool deleteConfig)
+ public void SendHideShowCommand()
+ {
+ HideShowCommand?.Invoke(this, null);
+ }
+
+ public event EventHandler ExitCommand;
+
+ public void SendExitCommand()
+ {
+ ExitCommand?.Invoke(this, null);
+ }
+
+ private void UpdateMainIconVisibility()
+ {
+ if (_mainIconEnabled)
+ _mainIcon.Visible = _sensorList.Count == 0;
+ else
+ _mainIcon.Visible = false;
+ }
+
+ public bool IsMainIconEnabled
+ {
+ get { return _mainIconEnabled; }
+ set
{
- if (deleteConfig)
+ if (_mainIconEnabled != value)
{
- _settings.Remove(new Identifier(sensor.Identifier, "tray").ToString());
- _settings.Remove(new Identifier(sensor.Identifier, "traycolor").ToString());
- }
- SensorNotifyIcon instance = null;
- foreach (SensorNotifyIcon icon in _sensorList)
- {
- if (icon.Sensor == sensor)
- instance = icon;
- }
- if (instance != null)
- {
- _sensorList.Remove(instance);
+ _mainIconEnabled = value;
UpdateMainIconVisibility();
- instance.Dispose();
- }
- }
-
- public event EventHandler HideShowCommand;
-
- public void SendHideShowCommand()
- {
- HideShowCommand?.Invoke(this, null);
- }
-
- public event EventHandler ExitCommand;
-
- public void SendExitCommand()
- {
- ExitCommand?.Invoke(this, null);
- }
-
- private void UpdateMainIconVisibility()
- {
- if (_mainIconEnabled)
- _mainIcon.Visible = _sensorList.Count == 0;
- else
- _mainIcon.Visible = false;
- }
-
- public bool IsMainIconEnabled
- {
- get { return _mainIconEnabled; }
- set
- {
- if (_mainIconEnabled != value)
- {
- _mainIconEnabled = value;
- UpdateMainIconVisibility();
- }
}
}
}
-}
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/ToolStripRadioButtonMenuItem.cs b/LibreHardwareMonitor/UI/ToolStripRadioButtonMenuItem.cs
index 29df43d..c1dacb9 100644
--- a/LibreHardwareMonitor/UI/ToolStripRadioButtonMenuItem.cs
+++ b/LibreHardwareMonitor/UI/ToolStripRadioButtonMenuItem.cs
@@ -3,253 +3,252 @@ using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+///
+/// https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-display-option-buttons-in-a-menustrip-windows-forms
+///
+public class ToolStripRadioButtonMenuItem : ToolStripMenuItem
{
- ///
- /// https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-display-option-buttons-in-a-menustrip-windows-forms
- ///
- public class ToolStripRadioButtonMenuItem : ToolStripMenuItem
+ public ToolStripRadioButtonMenuItem()
+ : base()
{
- public ToolStripRadioButtonMenuItem()
- : base()
+ Initialize();
+ }
+
+ public ToolStripRadioButtonMenuItem(string text)
+ : base(text, null, (EventHandler)null)
+ {
+ Initialize();
+ }
+
+ public ToolStripRadioButtonMenuItem(Image image)
+ : base(null, image, (EventHandler)null)
+ {
+ Initialize();
+ }
+
+ public ToolStripRadioButtonMenuItem(string text, Image image)
+ : base(text, image, (EventHandler)null)
+ {
+ Initialize();
+ }
+
+ public ToolStripRadioButtonMenuItem(string text, Image image,
+ EventHandler onClick)
+ : base(text, image, onClick)
+ {
+ Initialize();
+ }
+
+ public ToolStripRadioButtonMenuItem(string text, Image image,
+ EventHandler onClick, string name)
+ : base(text, image, onClick, name)
+ {
+ Initialize();
+ }
+
+ public ToolStripRadioButtonMenuItem(string text, Image image,
+ params ToolStripItem[] dropDownItems)
+ : base(text, image, dropDownItems)
+ {
+ Initialize();
+ }
+
+ public ToolStripRadioButtonMenuItem(string text, Image image,
+ EventHandler onClick, Keys shortcutKeys)
+ : base(text, image, onClick)
+ {
+ Initialize();
+ ShortcutKeys = shortcutKeys;
+ }
+
+ // Called by all constructors to initialize CheckOnClick.
+ private void Initialize()
+ {
+ CheckOnClick = true;
+ }
+
+ protected override void OnCheckedChanged(EventArgs e)
+ {
+ base.OnCheckedChanged(e);
+
+ // If this item is no longer in the checked state or if its
+ // parent has not yet been initialized, do nothing.
+ if (!Checked || Parent == null) return;
+
+ // Clear the checked state for all siblings.
+ foreach (ToolStripItem item in Parent.Items)
{
- Initialize();
- }
-
- public ToolStripRadioButtonMenuItem(string text)
- : base(text, null, (EventHandler)null)
- {
- Initialize();
- }
-
- public ToolStripRadioButtonMenuItem(Image image)
- : base(null, image, (EventHandler)null)
- {
- Initialize();
- }
-
- public ToolStripRadioButtonMenuItem(string text, Image image)
- : base(text, image, (EventHandler)null)
- {
- Initialize();
- }
-
- public ToolStripRadioButtonMenuItem(string text, Image image,
- EventHandler onClick)
- : base(text, image, onClick)
- {
- Initialize();
- }
-
- public ToolStripRadioButtonMenuItem(string text, Image image,
- EventHandler onClick, string name)
- : base(text, image, onClick, name)
- {
- Initialize();
- }
-
- public ToolStripRadioButtonMenuItem(string text, Image image,
- params ToolStripItem[] dropDownItems)
- : base(text, image, dropDownItems)
- {
- Initialize();
- }
-
- public ToolStripRadioButtonMenuItem(string text, Image image,
- EventHandler onClick, Keys shortcutKeys)
- : base(text, image, onClick)
- {
- Initialize();
- ShortcutKeys = shortcutKeys;
- }
-
- // Called by all constructors to initialize CheckOnClick.
- private void Initialize()
- {
- CheckOnClick = true;
- }
-
- protected override void OnCheckedChanged(EventArgs e)
- {
- base.OnCheckedChanged(e);
-
- // If this item is no longer in the checked state or if its
- // parent has not yet been initialized, do nothing.
- if (!Checked || Parent == null) return;
-
- // Clear the checked state for all siblings.
- foreach (ToolStripItem item in Parent.Items)
+ if (item is ToolStripRadioButtonMenuItem radioItem
+ && radioItem != this
+ && radioItem.Checked)
{
- if (item is ToolStripRadioButtonMenuItem radioItem
- && radioItem != this
- && radioItem.Checked)
- {
- radioItem.Checked = false;
+ radioItem.Checked = false;
- // Only one item can be selected at a time,
- // so there is no need to continue.
- return;
- }
- }
- }
-
- protected override void OnClick(EventArgs e)
- {
- // If the item is already in the checked state, do not call
- // the base method, which would toggle the value.
- if (Checked) return;
-
- base.OnClick(e);
- }
-
- // Let the item paint itself, and then paint the RadioButton
- // where the check mark is normally displayed.
- protected override void OnPaint(PaintEventArgs e)
- {
- if (Image != null)
- {
- // If the client sets the Image property, the selection behavior
- // remains unchanged, but the RadioButton is not displayed and the
- // selection is indicated only by the selection rectangle.
- base.OnPaint(e);
+ // Only one item can be selected at a time,
+ // so there is no need to continue.
return;
}
- else
- {
- // If the Image property is not set, call the base OnPaint method
- // with the CheckState property temporarily cleared to prevent
- // the check mark from being painted.
- CheckState currentState = CheckState;
- CheckState = CheckState.Unchecked;
- base.OnPaint(e);
- CheckState = currentState;
- }
+ }
+ }
- // Determine the correct state of the RadioButton.
- RadioButtonState buttonState = RadioButtonState.UncheckedNormal;
- if (Enabled)
+ protected override void OnClick(EventArgs e)
+ {
+ // If the item is already in the checked state, do not call
+ // the base method, which would toggle the value.
+ if (Checked) return;
+
+ base.OnClick(e);
+ }
+
+ // Let the item paint itself, and then paint the RadioButton
+ // where the check mark is normally displayed.
+ protected override void OnPaint(PaintEventArgs e)
+ {
+ if (Image != null)
+ {
+ // If the client sets the Image property, the selection behavior
+ // remains unchanged, but the RadioButton is not displayed and the
+ // selection is indicated only by the selection rectangle.
+ base.OnPaint(e);
+ return;
+ }
+ else
+ {
+ // If the Image property is not set, call the base OnPaint method
+ // with the CheckState property temporarily cleared to prevent
+ // the check mark from being painted.
+ CheckState currentState = CheckState;
+ CheckState = CheckState.Unchecked;
+ base.OnPaint(e);
+ CheckState = currentState;
+ }
+
+ // Determine the correct state of the RadioButton.
+ RadioButtonState buttonState = RadioButtonState.UncheckedNormal;
+ if (Enabled)
+ {
+ if (mouseDownState)
{
- if (mouseDownState)
- {
- if (Checked)
- buttonState = RadioButtonState.CheckedPressed;
- else
- buttonState = RadioButtonState.UncheckedPressed;
- }
- else if (mouseHoverState)
- {
- if (Checked)
- buttonState = RadioButtonState.CheckedHot;
- else
- buttonState = RadioButtonState.UncheckedHot;
- }
+ if (Checked)
+ buttonState = RadioButtonState.CheckedPressed;
else
- {
- if (Checked)
- buttonState = RadioButtonState.CheckedNormal;
- }
+ buttonState = RadioButtonState.UncheckedPressed;
+ }
+ else if (mouseHoverState)
+ {
+ if (Checked)
+ buttonState = RadioButtonState.CheckedHot;
+ else
+ buttonState = RadioButtonState.UncheckedHot;
}
else
{
if (Checked)
- buttonState = RadioButtonState.CheckedDisabled;
- else
- buttonState = RadioButtonState.UncheckedDisabled;
+ buttonState = RadioButtonState.CheckedNormal;
}
-
- // Calculate the position at which to display the RadioButton.
- int offset = (ContentRectangle.Height -
- RadioButtonRenderer.GetGlyphSize(
- e.Graphics, buttonState).Height) / 2;
-
- Point imageLocation = new Point(
- ContentRectangle.Location.X + 4,
- ContentRectangle.Location.Y + offset);
-
- // Paint the RadioButton.
- RadioButtonRenderer.DrawRadioButton(e.Graphics, imageLocation, buttonState);
+ }
+ else
+ {
+ if (Checked)
+ buttonState = RadioButtonState.CheckedDisabled;
+ else
+ buttonState = RadioButtonState.UncheckedDisabled;
}
- private bool mouseHoverState;
+ // Calculate the position at which to display the RadioButton.
+ int offset = (ContentRectangle.Height -
+ RadioButtonRenderer.GetGlyphSize(
+ e.Graphics, buttonState).Height) / 2;
- protected override void OnMouseEnter(EventArgs e)
+ Point imageLocation = new Point(
+ ContentRectangle.Location.X + 4,
+ ContentRectangle.Location.Y + offset);
+
+ // Paint the RadioButton.
+ RadioButtonRenderer.DrawRadioButton(e.Graphics, imageLocation, buttonState);
+ }
+
+ private bool mouseHoverState;
+
+ protected override void OnMouseEnter(EventArgs e)
+ {
+ mouseHoverState = true;
+
+ // Force the item to repaint with the new RadioButton state.
+ Invalidate();
+
+ base.OnMouseEnter(e);
+ }
+
+ protected override void OnMouseLeave(EventArgs e)
+ {
+ mouseHoverState = false;
+ base.OnMouseLeave(e);
+ }
+
+ private bool mouseDownState;
+
+ protected override void OnMouseDown(MouseEventArgs e)
+ {
+ mouseDownState = true;
+
+ // Force the item to repaint with the new RadioButton state.
+ Invalidate();
+
+ base.OnMouseDown(e);
+ }
+
+ protected override void OnMouseUp(MouseEventArgs e)
+ {
+ mouseDownState = false;
+ base.OnMouseUp(e);
+ }
+
+ // Enable the item only if its parent item is in the checked state
+ // and its Enabled property has not been explicitly set to false.
+ public override bool Enabled
+ {
+ get
{
- mouseHoverState = true;
-
- // Force the item to repaint with the new RadioButton state.
- Invalidate();
-
- base.OnMouseEnter(e);
- }
-
- protected override void OnMouseLeave(EventArgs e)
- {
- mouseHoverState = false;
- base.OnMouseLeave(e);
- }
-
- private bool mouseDownState;
-
- protected override void OnMouseDown(MouseEventArgs e)
- {
- mouseDownState = true;
-
- // Force the item to repaint with the new RadioButton state.
- Invalidate();
-
- base.OnMouseDown(e);
- }
-
- protected override void OnMouseUp(MouseEventArgs e)
- {
- mouseDownState = false;
- base.OnMouseUp(e);
- }
-
- // Enable the item only if its parent item is in the checked state
- // and its Enabled property has not been explicitly set to false.
- public override bool Enabled
- {
- get
+ // Use the base value in design mode to prevent the designer
+ // from setting the base value to the calculated value.
+ if (!DesignMode
+ && OwnerItem is ToolStripMenuItem ownerMenuItem
+ && ownerMenuItem.CheckOnClick)
{
- // Use the base value in design mode to prevent the designer
- // from setting the base value to the calculated value.
- if (!DesignMode
- && OwnerItem is ToolStripMenuItem ownerMenuItem
- && ownerMenuItem.CheckOnClick)
- {
- return base.Enabled && ownerMenuItem.Checked;
- }
- else
- {
- return base.Enabled;
- }
+ return base.Enabled && ownerMenuItem.Checked;
}
- set
+ else
{
- base.Enabled = value;
+ return base.Enabled;
}
}
-
- // When OwnerItem becomes available, if it is a ToolStripMenuItem
- // with a CheckOnClick property value of true, subscribe to its
- // CheckedChanged event.
- protected override void OnOwnerChanged(EventArgs e)
+ set
{
- if (OwnerItem is ToolStripMenuItem ownerMenuItem
- && ownerMenuItem.CheckOnClick)
- {
- ownerMenuItem.CheckedChanged +=
- new EventHandler(OwnerMenuItem_CheckedChanged);
- }
- base.OnOwnerChanged(e);
- }
-
- // When the checked state of the parent item changes,
- // repaint the item so that the new Enabled state is displayed.
- private void OwnerMenuItem_CheckedChanged(object sender, EventArgs e)
- {
- Invalidate();
+ base.Enabled = value;
}
}
-}
+
+ // When OwnerItem becomes available, if it is a ToolStripMenuItem
+ // with a CheckOnClick property value of true, subscribe to its
+ // CheckedChanged event.
+ protected override void OnOwnerChanged(EventArgs e)
+ {
+ if (OwnerItem is ToolStripMenuItem ownerMenuItem
+ && ownerMenuItem.CheckOnClick)
+ {
+ ownerMenuItem.CheckedChanged +=
+ new EventHandler(OwnerMenuItem_CheckedChanged);
+ }
+ base.OnOwnerChanged(e);
+ }
+
+ // When the checked state of the parent item changes,
+ // repaint the item so that the new Enabled state is displayed.
+ private void OwnerMenuItem_CheckedChanged(object sender, EventArgs e)
+ {
+ Invalidate();
+ }
+}
\ No newline at end of file
diff --git a/LibreHardwareMonitor/UI/TreeModel.cs b/LibreHardwareMonitor/UI/TreeModel.cs
index 9a7b6f4..6675ab7 100644
--- a/LibreHardwareMonitor/UI/TreeModel.cs
+++ b/LibreHardwareMonitor/UI/TreeModel.cs
@@ -10,117 +10,116 @@ using System.Collections.Generic;
using System.Collections.ObjectModel;
using Aga.Controls.Tree;
-namespace LibreHardwareMonitor.UI
+namespace LibreHardwareMonitor.UI;
+
+public class TreeModel : ITreeModel
{
- public class TreeModel : ITreeModel
+ private readonly Node _root;
+ private bool _forceVisible;
+
+ public TreeModel()
{
- private readonly Node _root;
- private bool _forceVisible;
+ _root = new Node { Model = this };
+ }
- public TreeModel()
+ public TreePath GetPath(Node node)
+ {
+ if (node == _root)
+ return TreePath.Empty;
+
+
+ Stack