我对C ++很新,还在学习。 试图接近例子。但仍然。 在最后一步,我的uReturn为空,所以我得不到我想要的信息。 我错了某处或什么? 感谢您提供的任何帮助!
#include "stdafx.h"
#define _WIN32_DCOM
#include <iostream>
#include <wbemidl.h>
#include <comdef.h>
# pragma comment(lib, "wbemuuid.lib")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hres;
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x"
<< hex << hres << endl;
return hres;
}
cout << "COM library initialization OK \n";
hres = CoInitializeSecurity
(
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_DEFAULT,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
NULL
);
if (FAILED(hres))
{
CoUninitialize();
cout << "Failed to initialize security. Error code = 0x"
<< hex << hres << endl;
return 1;
}
cout << "COM security initialization OK \n";
IWbemLocator *pLoc = NULL;
hres = CoCreateInstance
(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator,
(LPVOID *)&pLoc
);
if (FAILED(hres))
{
cout << "Failed to create IWbemLocator object. Err code = 0x"
<< hex << hres << endl;
CoUninitialize();
return hres;
}
cout << "IWbemLocator initialization OK \n";
IWbemServices *pSvc = NULL;
hres = pLoc->ConnectServer
(
_bstr_t(L"ROOT\\DEFAULT"),
NULL,
NULL,
0,
NULL,
0,
0,
&pSvc
);
if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x"
<< hex << hres << endl;
pLoc->Release();
CoUninitialize();
return 1;
}
cout << "Connected to WMI \n";
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 = 0x"
<< hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1;
}
cout << "Security levels on a WMI connection SET \n";
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery
(
bstr_t("WQL"),
bstr_t("SELECT * FROM Win32_OperatingSystem"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator
);
if (FAILED(hres))
{
cout << "Query for operating system name failed."
<< " Error code = 0x"
<< hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1;
}
cout << "Query OK! \n";
IWbemClassObject *pclsObj;
ULONG uReturn = 0;
while (pEnumerator)
{
cout << "Getting Value... \n";
HRESULT hr = pEnumerator->Next
(
WBEM_INFINITE,
1,
&pclsObj,
&uReturn
);
if (0 == uReturn)
{
cout << "uReturn is NULL! Breaking! \n";
break;
}
VARIANT vtProp;
hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
cout << " OS Name : " << vtProp.bstrVal << endl;
VariantClear(&vtProp);
pclsObj->Release();
}
cout << "Completed! Cleaning up! \n";
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
CoUninitialize();
return 0;
}