C#获取CPU温度(OpenHardwareMonitorLib.dll库)

作者尝试过WinIo,Rdmsr,WMI,OpenHardwareMonitorLib。OpenHardwareMonitorLib和rdmsr都是用的WinRing0.sys驱动,然后要在程序里面加载这个驱动就可读取这些寄存器的值。OpenHardwareMonitorLib把驱动封装到自己的内部来了,这里讲的是OpenHardwareMonitorLib的方法,很简单:

OpenHardwareMonitorLib.dll下载地址:https://download.csdn.net/download/u014597198/11106339

1、下载OpenHardwareMonitorLib库,并引用到项目中

2、读取温度,这里只读取了一次,如果需要你可以用定时器轮询:

using System;
using OpenHardwareMonitor.Hardware;
using System.Text;

namespace VS_ReadCPUTemperature
{
    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) { }
    }
    class Program
    {
        static int getTemperature() 
        {
            int ret = 0;
            Computer myComputer = new Computer();
            UpdateVisitor updateVisitor = new UpdateVisitor();
            myComputer.Open();
            myComputer.Accept(updateVisitor);
            foreach (var hardwareItem in myComputer.Hardware)
            {
                if (hardwareItem.HardwareType == HardwareType.CPU)
                {
                    foreach (var sensor in hardwareItem.Sensors)
                    {
                        if (sensor.SensorType == SensorType.Temperature)
                        {
                            ret = Convert.ToInt32(sensor.Value);
                        }
                    }
                }
            }
            return ret;
        } 
        static void Main(string[] args)
        {
            int t = getTemperature();
            Console.WriteLine("温度是:" + t);
            Console.ReadKey();

            //如果文件不存在,则创建;存在则覆盖
            //System.IO.File.WriteAllText(@"C:\Users\Public\Documents\CPUTemperature.txt", t.ToString(), Encoding.UTF8);
        }
    }
}

 

发布了261 篇原创文章 · 获赞 734 · 访问量 223万+
展开阅读全文

这是一个C++写的Windows下读取CPU温度的程序但是读不出来温度啊?

05-18

我是VC6写的代码如下 顺便问下大家谁有读windows的CPU占用率和内存占用的程序 小弟很急啊 在线等希望各位大神能够出手帮助啊 #include "stdafx.h" #include "CPUTemperature.h" #include "CPUTemperatureDlg.h" #include <Windows.h> #include <Winsvc.h> #include <WinIoCtl.h> #ifdef _DEBUG #define new DEBUG_NEW #endif #define MYWINRIN0 _T("MyWinRing0") #define OLS_DRIVER_ID _T("WinRing0_1_2_0") #define OLS_TYPE 40000 #define IOCTL_OLS_READ_MSR \ CTL_CODE(OLS_TYPE, 0x821, METHOD_BUFFERED, FILE_ANY_ACCESS) BOOL gIsMsr = TRUE; TCHAR gDriverPath[MAX_PATH]; HANDLE gHandle = INVALID_HANDLE_VALUE; void LoadDriver(); BOOL StopDriver(SC_HANDLE hSCManager,LPCTSTR DriverId); BOOL RemoveDriver(SC_HANDLE hSCManager, LPCTSTR DriverId); BOOL IsFileExist(LPCTSTR fileName); BOOL Initialize(); void LoadDriver(); BOOL OpenDriver(); void Remove(); BOOL WINAPI Rdmsr(DWORD index, PDWORD eax, PDWORD edx); CCPUTemperatureDlg::CCPUTemperatureDlg(CWnd* pParent /*=NULL*/) : CDialog(CCPUTemperatureDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CCPUTemperatureDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CCPUTemperatureDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_WM_TIMER() END_MESSAGE_MAP() BOOL CCPUTemperatureDlg::OnInitDialog() { CDialog::OnInitDialog(); SetTimer(123,1000,NULL); Remove(); Initialize(); return TRUE; } void Remove() { SC_HANDLE hSCManager = NULL; hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); StopDriver(hSCManager,MYWINRIN0); RemoveDriver(hSCManager,MYWINRIN0); CloseServiceHandle(hSCManager); } //打开驱动 BOOL OpenDriver() { char message[256]="0"; char *str=_T("\\\\.\\") OLS_DRIVER_ID ; gHandle = CreateFile( _T("\\\\.\\") OLS_DRIVER_ID, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); int code=GetLastError(); if(gHandle == INVALID_HANDLE_VALUE) { return FALSE; } return TRUE; } BOOL Initialize() { TCHAR dir[MAX_PATH]; TCHAR *ptr; GetModuleFileName(NULL, dir, MAX_PATH); if((ptr = _tcsrchr(dir, '\\')) != NULL) { *ptr = '\0'; } wsprintf(gDriverPath, _T("%s\\%s"), dir, _T("WinRing0.sys")); if(IsFileExist(gDriverPath) == FALSE) { return FALSE; } if(OpenDriver()) { return TRUE; } else { LoadDriver(); OpenDriver(); } } BOOL IsFileExist(LPCTSTR fileName) { WIN32_FIND_DATA findData; HANDLE hFile = FindFirstFile(fileName, &findData); if(hFile != INVALID_HANDLE_VALUE) { FindClose( hFile ); return TRUE; } else { return FALSE; } } //加载驱动 void LoadDriver() { SC_HANDLE hSCManager = NULL; SC_HANDLE hService = NULL; SC_HANDLE hService1 = NULL; hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); hService = CreateService(hSCManager, MYWINRIN0, MYWINRIN0, SERVICE_ALL_ACCESS, SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, gDriverPath, NULL, NULL, NULL, NULL, NULL ); CloseServiceHandle(hService); hService1 = OpenService(hSCManager, MYWINRIN0, SERVICE_ALL_ACCESS); int result=StartService(hService1, 0, NULL); CloseServiceHandle(hSCManager); CloseServiceHandle(hService1); } BOOL StopDriver(SC_HANDLE hSCManager,LPCTSTR DriverId) { SC_HANDLE hService = NULL; BOOL rCode = FALSE; SERVICE_STATUS serviceStatus; DWORD error = NO_ERROR; hService = OpenService(hSCManager, DriverId, SERVICE_ALL_ACCESS); if(hService != NULL) { rCode = ControlService(hService, SERVICE_CONTROL_STOP, &serviceStatus); error = GetLastError(); CloseServiceHandle(hService); } return rCode; } BOOL RemoveDriver(SC_HANDLE hSCManager, LPCTSTR DriverId) { SC_HANDLE hService = NULL; BOOL rCode = FALSE; hService = OpenService(hSCManager, DriverId, SERVICE_ALL_ACCESS); if(hService == NULL) { rCode = TRUE; } else { rCode = DeleteService(hService); CloseServiceHandle(hService); } return rCode; } DWORD GetCpuInfo( DWORD veax) { DWORD deax, debx, decx, dedx; __asm { push eax; push ebx; push ecx; push edx; mov eax, veax; cpuid; mov deax, eax; mov debx, ebx; mov decx, ecx; mov dedx, edx; pop edx; pop ecx; pop ebx; pop eax; } return deax; } //读取msr寄存器 BOOL WINAPI Rdmsr(DWORD index, PDWORD eax, PDWORD edx) { if(gHandle == INVALID_HANDLE_VALUE) { return FALSE; } if(eax == NULL || edx == NULL || gIsMsr == FALSE) { return FALSE; } DWORD returnedLength = 0; BOOL result = FALSE; BYTE outBuf[8] = {0}; result = DeviceIoControl( gHandle, IOCTL_OLS_READ_MSR, &index, sizeof(index), &outBuf, sizeof(outBuf), &returnedLength, NULL ); if(result) { memcpy(eax, outBuf, 4); memcpy(edx, outBuf + 4, 4); } if(result) { return TRUE; } else { return FALSE; } } void CCPUTemperatureDlg::OnCancel() { //卸载驱动 Remove(); CDialog::OnCancel(); } void CCPUTemperatureDlg::OnTimer(UINT_PTR nIDEvent) { DWORD eax_in; DWORD eax_out; eax_in= 1; eax_out= GetCpuInfo(eax_in); eax_in= 0; eax_out= GetCpuInfo(eax_in); eax_in= 6; eax_out= GetCpuInfo(eax_in); CEdit *edit=(CEdit*)GetDlgItem(IDC_EDIT1); CEdit *edit1=(CEdit*)GetDlgItem(IDC_EDIT2); DWORD eax=0,edx=0; ULONG result; char s[20]; Rdmsr(0xee,&eax,&edx); Rdmsr(0x1a2,&eax,&edx); result=SetThreadAffinityMask(GetCurrentThread(),1); Rdmsr(0x19c,&eax,&edx);//read Temperature //SetThreadAffinityMask(GetCurrentThread(),result); sprintf(s,"%d",100-((eax&0x007f0000)>>16)); SetThreadAffinityMask(GetCurrentThread(),result); edit->SetWindowText(s); result=SetThreadAffinityMask(GetCurrentThread(),2); Rdmsr(0x19c,&eax,&edx);//read Temperature SetThreadAffinityMask(GetCurrentThread(),result); sprintf(s,"%d",100-((eax&0x007f0000)>>16)); edit1->SetWindowText(s); CDialog::OnTimer(nIDEvent); } 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 代码科技 设计师: Amelia_0503

分享到微信朋友圈

×

扫一扫,手机浏览