C#实现读取硬件温度
利用了LibreHardwareMonitor的dll库文件,将该文件引用到工程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| using LibreHardwareMonitor.Hardware; using OpenHardwareMonitorApi; namespace TemperatureTest_WPF { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } public class UpdateVisitor : IVisitor { public void VisitComputer(IComputer computer) { computer.Traverse(this); } public void VisitHardware(IHardware hardware) { hardware.Update(); foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this); } public void VisitSensor(ISensor sensor) { } public void VisitParameter(IParameter parameter) { } } static int getTemperature() { int ret = 0; Computer myComputer = new Computer() { IsCpuEnabled = true, IsGpuEnabled = true,
}; UpdateVisitor updateVisitor = new UpdateVisitor(); myComputer.Open(); myComputer.Accept(updateVisitor); var gpuTemperature = myComputer.Hardware .FirstOrDefault(h => h.HardwareType == HardwareType.GpuNvidia)? .Sensors.FirstOrDefault(s => s.SensorType == SensorType.Temperature); if (gpuTemperature != null) { ret = Convert.ToInt32(gpuTemperature.Value); } return ret; }
private async void TempertureCheck_Click(object sender, RoutedEventArgs e) { int t = await GetTemperatureAsync(); TempertureDisplay.Text = t.ToString() + "度"; } private Task<int> GetTemperatureAsync() { return Task.Run(() => { int temperature = getTemperature(); return temperature; }); }
} }
|