Fixed possible crash

This commit is contained in:
seerge
2023-02-23 16:05:31 +01:00
parent 02ae48092b
commit 27f5ed50d5
3 changed files with 63 additions and 10 deletions

View File

@@ -13,6 +13,7 @@
<Platforms>AnyCPU;x64</Platforms>
<SupportedOSPlatformVersion>8.0</SupportedOSPlatformVersion>
<AssemblyName>GHelper</AssemblyName>
<PlatformTarget>AnyCPU</PlatformTarget>
</PropertyGroup>
<ItemGroup>

View File

@@ -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,

View File

@@ -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()
{
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();
}
}