用C++语言写一个获取CPU温度的代码
时间: 2024-05-19 22:14:48 浏览: 26
我建议您使用 WMI(Windows Management Instrumentation) API 来获取 CPU 温度。下面是一种用 C 语言编写的代码: #include <windows.h>
#include <stdio.h>
int main()
{
IWbemLocator *locator = NULL;
HRESULT hr;
hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, __uuidof(IWbemLocator), (LPVOID *)&locator);
if (FAILED(hr))
{
printf("Failed to create IWbemLocator object. Err = 0x%08lx\n", hr);
return -1;
}
IWbemServices *services = NULL;
hr = locator->ConnectServer(L"root\\OpenHardwareMonitor", NULL, NULL, 0, 0, 0, 0, &services);
if (FAILED(hr))
{
printf("Failed to connect. Error code = 0x%08lx\n", hr);
return -1;
}
CoSetProxyBlanket(services, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
IEnumWbemClassObject *classObject = NULL;
hr = services->ExecQuery(L"SELECT * FROM Sensor WHERE SensorType=\"Temperature\"", WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &classObject);
if (FAILED(hr))
{
printf("Query for hardware failed. Error code = 0x%08lx\n", hr);
return -1;
}
IWbemClassObject *object = NULL;
ULONG returnCount = 0;
while ((hr = classObject->Next(WBEM_INFINITE, 1, &object, &returnCount)) == S_OK)
{
VARIANT value;
hr = object->Get(L"Value", 0, &value, 0, 0);
if (FAILED(hr))
{
printf("Failed to get temperature. Error code = 0x%08lx\n", hr);
return -1;
}
else
{
printf("Current CPU temperature: %f\n", value.fltVal);
}
VariantClear(&value);
object->Release();
}
classObject->Release();
services->Release();
locator->Release();
CoUninitialize();
return 0;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)