From 27f5ed50d5d3f095557844b7732d1aaa6d1824dc Mon Sep 17 00:00:00 2001 From: seerge Date: Thu, 23 Feb 2023 16:05:31 +0100 Subject: [PATCH] Fixed possible crash --- GHelper.csproj | 1 + NativeMethods.cs | 35 ++++++++++++++++++++++++++++++++++- Program.cs | 37 ++++++++++++++++++++++++++++--------- 3 files changed, 63 insertions(+), 10 deletions(-) diff --git a/GHelper.csproj b/GHelper.csproj index 89db6249..721d74ab 100644 --- a/GHelper.csproj +++ b/GHelper.csproj @@ -13,6 +13,7 @@ AnyCPU;x64 8.0 GHelper + AnyCPU diff --git a/NativeMethods.cs b/NativeMethods.cs index 839251dd..4eb9adc3 100644 --- a/NativeMethods.cs +++ b/NativeMethods.cs @@ -1,8 +1,41 @@ -using System.Runtime.InteropServices; +using System.Diagnostics; +using System.Runtime.InteropServices; public class NativeMethods { + + [DllImport("user32.dll")] + public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); + public const int SW_RESTORE = 9; + + public static bool SwitchToCurrent() + { + IntPtr hWnd = IntPtr.Zero; + Process process = Process.GetCurrentProcess(); + Process[] processes = Process.GetProcessesByName(process.ProcessName); + foreach (Process _process in processes) + { + if (_process.Id != process.Id) + { + + if (_process.MainWindowHandle != IntPtr.Zero) + { + Debug.WriteLine(_process.Id); + Debug.WriteLine(process.Id); + + hWnd = _process.MainWindowHandle; + ShowWindowAsync(hWnd, SW_RESTORE); + } + + return true; + break; + } + } + + return false; + } + [DllImport("PowrProf.dll", CharSet = CharSet.Unicode)] static extern UInt32 PowerWriteDCValueIndex(IntPtr RootPowerKey, [MarshalAs(UnmanagedType.LPStruct)] Guid SchemeGuid, diff --git a/Program.cs b/Program.cs index 76f7b9be..c495db32 100644 --- a/Program.cs +++ b/Program.cs @@ -1,6 +1,7 @@ using LibreHardwareMonitor.Hardware; using System.Diagnostics; using System.Management; +using System.Security.Principal; using System.Text.Json; @@ -106,22 +107,40 @@ public class HardwareMonitor public float? batteryDischarge = -1; public float? batteryCharge = -1; + public static bool IsAdministrator() + { + return (new WindowsPrincipal(WindowsIdentity.GetCurrent())) + .IsInRole(WindowsBuiltInRole.Administrator); + } + public HardwareMonitor() { - computer = new Computer - { - IsCpuEnabled = true, - IsGpuEnabled = true, - IsBatteryEnabled = true, - }; } public void ReadSensors() { - computer.Open(); - computer.Accept(new UpdateVisitor()); + try + { + if (computer is not Computer) + { + computer = new Computer + { + IsGpuEnabled = true, + IsBatteryEnabled = true, + }; + + if (IsAdministrator()) computer.IsCpuEnabled = true; + } + + computer.Open(); + computer.Accept(new UpdateVisitor()); + } catch + { + Debug.WriteLine("Failed to read sensors"); + } + cpuTemp = -1; gpuTemp = -1; @@ -173,7 +192,7 @@ public class HardwareMonitor public void StopReading() { - computer.Close(); + //computer.Close(); } }