windows 编程获取cpu温度
时间: 2023-07-27 21:05:48 浏览: 144
在Windows编程中获取CPU温度需要通过系统WMI接口来实现。以下是一个示例代码,可以获取CPU温度信息:
```C++
#include <iostream>
#include <comdef.h>
#include <Wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")
int main()
{
HRESULT hres;
// COM初始化
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
std::cerr << "Failed to initialize COM library. Error code = 0x"
<< std::hex << hres << std::endl;
return 1;
}
// 访问WMI
hres = CoInitializeSecurity(
NULL,
-1, // COM库自己决定使用哪种安全级别
NULL, // 认证服务
NULL, // 保留
RPC_C_AUTHN_LEVEL_DEFAULT, // 身份验证级别
RPC_C_IMP_LEVEL_IMPERSONATE, // 根据代理访问权限
NULL, // 保留
EOAC_NONE, // 不做额外的安全检查
NULL // 保留
);
if (FAILED(hres))
{
std::cerr << "Failed to initialize security. Error code = 0x"
<< std::hex << hres << std::endl;
CoUninitialize();
return 1;
}
IWbemLocator* pLoc = NULL;
// 初始化WMI定位器
hres = CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator,
(LPVOID*)&pLoc
);
if (FAILED(hres))
{
std::cerr << "Failed to create IWbemLocator object. Error code = 0x"
<< std::hex << hres << std::endl;
CoUninitialize();
return 1;
}
IWbemServices* pSvc = NULL;
// 连接到WMI
hres = pLoc->ConnectServer(
_bstr_t(L"ROOT\\WMI"),
NULL,
NULL,
0,
NULL,
0,
0,
&pSvc
);
if (FAILED(hres))
{
std::cerr << "Could not connect. Error code = 0x"
<< std::hex << hres << std::endl;
pLoc->Release();
CoUninitialize();
return 1;
}
// 设置安全级别
hres = 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(hres))
{
std::cerr << "Could not set proxy blanket. Error code = 0x"
<< std::hex << hres << std::endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1;
}
// 查询CPU温度信息
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT * FROM MSAcpi_ThermalZoneTemperature"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator
);
if (FAILED(hres))
{
std::cerr << "Query failed. Error code = 0x"
<< std::hex << hres << std::endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1;
}
// 枚举获取CPU温度信息
IWbemClassObject* pObj = NULL;
ULONG uReturn = 0;
VARIANT vtProp;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pObj, &uReturn);
if (0 == uReturn)
{
break;
}
// 获取CPU温度信息
hr = pObj->Get(L"CurrentTemperature", 0, &vtProp, 0, 0);
if (SUCCEEDED(hr))
{
int temp = vtProp.lVal - 2732; // 转换为摄氏度
std::cout << "CPU temperature: " << temp << " C" << std::endl;
}
VariantClear(&vtProp);
pObj->Release();
}
// 清理资源
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
CoUninitialize();
return 0;
}
```
注意:该代码需要以管理员权限运行才能获取到正确的CPU温度信息。另外,获取CPU温度信息的方式可能因不同的硬件平台而有所不同,需要根据具体情况进行调整。
阅读全文