qt 读取windowscpu温度
时间: 2023-10-11 16:11:58 浏览: 261
您可以使用 WMI (Windows Management Instrumentation) 来读取 Windows CPU 温度。以下是一个示例代码片段:
```c++
#include <windows.h>
#include <ole2.h>
#include <wbemidl.h>
#include <iostream>
using namespace std;
int main()
{
HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hr))
{
cerr << "Failed to initialize COM library" << endl;
return -1;
}
hr = CoInitializeSecurity(
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
NULL);
if (FAILED(hr))
{
CoUninitialize();
cerr << "Failed to initialize security" << endl;
return -1;
}
IWbemLocator* pLoc = NULL;
hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
if (FAILED(hr))
{
CoUninitialize();
cerr << "Failed to create IWbemLocator object" << endl;
return -1;
}
IWbemServices* pSvc = NULL;
hr = pLoc->ConnectServer(
_bstr_t(L"ROOT\\WMI"),
NULL,
NULL,
0,
NULL,
0,
0,
&pSvc);
if (FAILED(hr))
{
pLoc->Release();
CoUninitialize();
cerr << "Failed to ConnectServer" << endl;
return -1;
}
hr = CoSetProxyBlanket(
pSvc,
RPC_C_AUTHN_WINNT,
RPC_C_AUTHZ_NONE,
NULL,
RPC_C_AUTHN_LEVEL_CALL,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE);
if (FAILED(hr))
{
pSvc->Release();
pLoc->Release();
CoUninitialize();
cerr << "Failed to set proxy blanket" << endl;
return -1;
}
IEnumWbemClassObject* pEnumerator = NULL;
hr = pSvc->ExecQuery(
_bstr_t(L"WQL"),
_bstr_t(L"SELECT * FROM MSAcpi_ThermalZoneTemperature"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
if (FAILED(hr))
{
pSvc->Release();
pLoc->Release();
CoUninitialize();
cerr << "Failed to execute query" << endl;
return -1;
}
IWbemClassObject* pClsObj = NULL;
ULONG uReturn = 0;
while (pEnumerator)
{
hr = pEnumerator->Next(WBEM_INFINITE, 1, &pClsObj, &uReturn);
if (uReturn == 0)
break;
VARIANT vtTemperature;
hr = pClsObj->Get(L"CurrentTemperature", 0, &vtTemperature, NULL, NULL);
if (SUCCEEDED(hr))
{
int nTemperature = vtTemperature.intVal / 10 - 273;
cout << "CPU temperature: " << nTemperature << "℃" << endl;
}
VariantClear(&vtTemperature);
pClsObj->Release();
}
pEnumerator->Release();
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 0;
}
```
此代码将读取 `MSAcpi_ThermalZoneTemperature` WMI 类中 `CurrentTemperature` 属性的值,该属性表示当前的温度。由于这个值以 0.1 摄氏度为单位,并且以开尔文为单位,则需要进行适当的计算,以将其转换为摄氏度。
阅读全文