C#获取CPU温度支持Win10

【已解决】C#获取CPU温度支持Win10(OpenHardwareMonitor)

本方法Win10 64bit 亲身测试可用,温度可以实时更新!!

很久前在Win8实现过远程CPU温度监控,用的是WMI方法,感觉简单易用。

现在换上了Win10,发现获取到的温度一直不会变,于是找到了http://blog.csdn.net/yanpingsoft/article/details/8754679 提到了OpenHardwareMonitor,于是就尝试了一下,但发现了一个问题:只有先运行现成的OpenHardwareMonitor.exe,我的C#程序才能读到温度值,否则为null。情况跟http://bbs.csdn.net/topics/391007951?page=1的一样。

搞了许久,没头绪,于是打算更新下OpenHardwareMonitor的库。于是网上百度“OpenHardwareMonitor”,找到最新的0.8.0beta的版本,下载替换了OpenHardwareMonitorLib.dll。试了下发现不能兼容,所以稍微改下代码,增加一句:computer.CPUEnabled = true;就完事了。完整的使用代码如下:

1、添加引用OpenHardwareMonitorLib.dll,添加using OpenHardwareMonitor.Hardware;

2、增加一个类

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) { }
    }

3、具体实现代码:

private void button1_Click(object sender, EventArgs e)//某个按键触发
        {

            UpdateVisitor updateVisitor = new UpdateVisitor();
            Computer computer = new Computer();
            computer.Open();
            computer.CPUEnabled = true;
            computer.Accept(updateVisitor);
            for (int i = 0; i < computer.Hardware.Length; i++)
            {
                //循环找到HardwareType为cpu
                if (computer.Hardware[i].HardwareType == HardwareType.CPU)
                {
                    for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
                    {
                        //找到温度
                        if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
                        {
                            if (computer.Hardware[i].Sensors[j].Name == "CPU Package")  //我只获取整个package的温度,需要其他core的温度就改这里
                                Console.WriteLine("Tem=" + computer.Hardware[i].Sensors[j].Value.ToString());
                        }
                    }
                }
            }
            computer.Close();
        }

猜你喜欢

转载自blog.csdn.net/u013934107/article/details/84335306
今日推荐