在 C++ 中,存在一组类库用于管理计算机上的硬件和软件资源,其中就包括 ManagementClass 类。ManagementClass 类是用于访问操作系统 WMI(Windows Management Instrumentation)服务的一种类,可以帮助程序员查询和修改系统信息。
简单来说,通过 ManagementClass 类,我们可以使用 WMI 查询并获得各种硬件和软件信息,如 CPU 架构、硬盘空间、进程信息等等。同时,也可以通过该类跟踪系统事件,例如登录/注销、磁盘空间的变化等。下面将对 ManagementClass 类的使用方法、常见应用场景以及一些示例代码进行详细介绍。
使用方法
首先,我们需要在代码中添加头文件"wbemidl.h",然后定义一个 ManagementClass 对象。接下来,我们就可以通过该对象的方法进行对象查询、属性查询和方法调用等操作。ManagementClass 类中常用的方法包括:
1. CreateInstanceEnum method:通过指定 WQL 查询语句获取 ManagementObjectCollection 对象。
2. Get method:获取指定对象的属性或者方法。
3. InvokeMethod method:调用对象的方法。
下面以查询硬件信息为例进行说明。
示例1:查询 CPU 信息
在这个示例中,我们会使用 ManagementClass 类查询和输出 CPU 的名称、厂商、核心数和占用率等信息。此外,我们还会使用 CPU 占用率信息来实现一个简单的系统性能监控应用程序。请注意,示例代码中的异常处理被忽略了。
#include #include #pragma comment(lib, "wbemuuid.lib") using namespace std; int main() { HRESULT hres; // Initialize COM library hres = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hres)) { cout << "Failed to initialize COM library. Error code: " << hres << endl; return 1; } // Initialize security hres = CoInitializeSecurity( NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL ); if (FAILED(hres)) { cout << "Failed to initialize security. Error code: " << hres << endl; CoUninitialize(); return 1; } // Initialize pointers IWbemLocator* pLoc = NULL; IWbemServices* pSvc = NULL; IEnumWbemClassObject* pEnumerator = NULL; IWbemClassObject* pclsObj = NULL; // Connect to the WMI locatocer hres = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc ); if (FAILED(hres)) { cout << "Failed to create IWbemLocator object. Error code: " << hres << endl; CoUninitialize(); return 1; } // Connect to the specified namespace hres = pLoc->ConnectServer( _bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc ); if (FAILED(hres)) { cout << "Could not connect to the specified namespace. Error code: " << hres << endl; pLoc->Release(); CoUninitialize(); return 1; } // Set up security to get full access 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)) { cout << "Could not set proxy blanket. Error code: " << hres << endl; pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; } // Prepare the WQL query hres = pSvc->ExecQuery( bstr_t("WQL"), bstr_t("SELECT * FROM Win32_Processor"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); if (FAILED(hres)) { cout << "Failed to execute WQL query. Error code: " << hres << endl; pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; } // Retrieve the data from the query ULONG uReturn = 0; VARIANT vtProp; while (pEnumerator) { HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) { break; } // Get the CPU name and manufacturer hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0); wcout << "CPU Name: " << vtProp.bstrVal << endl; VariantClear(&vtProp); hr = pclsObj->Get(L"Manufacturer", 0, &vtProp, 0, 0); wcout << "CPU Manufacturer: " << vtProp.bstrVal << endl; VariantClear(&vtProp); // Get the number of cores hr = pclsObj->Get(L"NumberOfCores", 0, &vtProp, 0, 0); cout << "Number of CPU cores: " << vtProp.iVal << endl; VariantClear(&vtProp); // Get the CPU usage SYSTEM_INFO sysInfo; GetSystemInfo(&sysInfo); DWORD numProcessors = sysInfo.dwNumberOfProcessors; PDH_STATUS status; HQUERY hQuery; HCOUNTER hCounter; DWORD dwCounterType; PDH_FMT_COUNTERVALUE counterVal; TCHAR counterPathBuffer[MAX_PATH]; // Connect to the PDH library status = PdhOpenQuery(NULL, 0, &hQuery); if (status != ERROR_SUCCESS) { cout << "Could not connect to PDH library. Error code: " << status << endl; pEnumerator->Release(); pclsObj->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; } // Get the counter path _stprintf_s(counterPathBuffer, MAX_PATH, _T("\\Processor(_Total)\\% Processor Time")); status = PdhAddCounter(hQuery, counterPathBuffer, 0, &hCounter); if (status != ERROR_SUCCESS) { cout << "Could not retrieve CPU counter path. Error code: " << status << endl; PdhCloseQuery(hQuery); pEnumerator->Release(); pclsObj->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; } // Collect the performance data status = PdhCollectQueryData(hQuery); if (status != ERROR_SUCCESS) { cout << "Could not collect performance data. Error code: " << status << endl; PdhCloseQuery(hQuery); pEnumerator->Release(); pclsObj->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; } Sleep(1000); // Get the counter value status = PdhCollectQueryData(hQuery); if (status != ERROR_SUCCESS) { cout << "Could not retrieve performance data. Error code: " << status << endl; PdhCloseQuery(hQuery); pEnumerator->Release(); pclsObj->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; } status = PdhGetFormattedCounterValue(hCounter, PDH_FMT_DOUBLE, &dwCounterType, &counterVal); if (status != ERROR_SUCCESS) { cout << "Could not format counter value. Error code: " << status << endl; PdhCloseQuery(hQuery); pEnumerator->Release(); pclsObj->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; } // Output the CPU usage printf("\n"); printf("\rCPU Usage: %.2f %%", counterVal.doubleValue / numProcessors); // Cleanup PdhCloseQuery(hQuery); pclsObj->Release(); } // Cleanup pEnumerator->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return 0; } 示例2:查询网络适配器信息 在这个示例中,我们会使用 ManagementClass 类查询和输出所有网络适配器的名称和 MAC 地址信息。 #include #include #pragma comment(lib, "wbemuuid.lib") using namespace std; int main() { HRESULT hres; // Initialize COM library hres = CoInitializeEx(0, COINIT_MULTITHREADED); if (FAILED(hres)) { cout << "Failed to initialize COM library. Error code: " << hres << endl; return 1; } // Initialize security hres = CoInitializeSecurity( NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL ); if (FAILED(hres)) { cout << "Failed to initialize security. Error code: " << hres << endl; CoUninitialize(); return 1; } // Initialize pointers IWbemLocator* pLoc = NULL; IWbemServices* pSvc = NULL; IEnumWbemClassObject* pEnumerator = NULL; IWbemClassObject* pclsObj = NULL; // Connect to the WMI locatocer hres = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc ); if (FAILED(hres)) { cout << "Failed to create IWbemLocator object. Error code: " << hres << endl; CoUninitialize(); return 1; } // Connect to the specified namespace hres = pLoc->ConnectServer( _bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc ); if (FAILED(hres)) { cout << "Could not connect to the specified namespace. Error code: " << hres << endl; pLoc->Release(); CoUninitialize(); return 1; } // Set up security to get full access 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)) { cout << "Could not set proxy blanket. Error code: " << hres << endl; pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; } // Prepare the WQL query hres = pSvc->ExecQuery( bstr_t("WQL"), bstr_t("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); if (FAILED(hres)) { cout << "Failed to execute WQL query. Error code: " << hres << endl; pSvc->Release(); pLoc->Release(); CoUninitialize(); return 1; } // Retrieve the data from the query ULONG uReturn = 0; VARIANT vtProp; while (pEnumerator) { HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); if (0 == uReturn) { break; } // Get the network adapter name and MAC address hr = pclsObj->Get(L"Caption", 0, &vtProp, 0, 0); wcout << "Network Adapter Name: " << vtProp.bstrVal << endl; VariantClear(&vtProp); hr = pclsObj->Get(L"MACAddress", 0, &vtProp, 0, 0); wcout << "MAC Address: " << vtProp.bstrVal << endl; VariantClear(&vtProp); // Cleanup pclsObj->Release(); } // Cleanup pEnumerator->Release(); pSvc->Release(); pLoc->Release(); CoUninitialize(); return 0; } 常见应用场景 ManagementClass 类可以用于许多方面的应用,下面是一些常见的应用场景: 1. 系统性能监控:通过查询计算机的 CPU 占用率、内存利用率和磁盘空间等信息,可以编写一个系统资源监控应用程序,可以汇总和显示有关系统资源使用情况的信息。 2. 硬件信息收集:通过查询计算机的硬件信息(如 CPU、内存、硬盘、显卡等),可以实现自动化系统信息收集任务,以辅助系统管理和故障排除等工作。 3. 系统事件跟踪:可以通过查询 Windows 事件日志、进程列表和服务状态等信息,实现系统事件的实时跟踪和警告的通知,以实现有效的系统监控。 4. 应用程序管理:可以通过查询系统中运行的进程和服务,以及系统上的安装软件列表,对软件漏洞扫描、系统管理和安全监控等工作提供帮助。 总结 通过 ManagementClass 类,我们可以以编程的方式访问 WMI 服务,从而轻松查询和修改系统信息。这些信息包括各种硬件和软件资源的信息、事件日志记录和系统配置等等,可以用于许多计算机管理和应用程序管理任务。值得注意的是,查询系统信息时,应该使用正确的查询语句,以防止查询失败或者查询结果出现意外错误。 如果你喜欢我们三七知识分享网站的文章,
欢迎您分享或收藏知识分享网站文章
欢迎您到我们的网站逛逛喔!https://www.37seo.cn/
你是我最深的思念,你是我无尽的挂牵,让风儿捎上我的祝福;让云儿带上我的问候:愿你度过一个幸福快乐的新年!