c++代码调用WMI 得到机器Model name.

以下samle code 是使用WMI的一个例子,可以得到Model.如果要得到BIOS的其它内容,可以改换参数。

#include
#include
#include
#include
#include
#include
#pragma comment(lib, "comsuppw.lib")

int main( int argc, TCHAR** argv )
{
    int result = 0;
 HRESULT hr = CoInitializeEx( NULL, COINIT_MULTITHREADED );
 if ( FAILED( hr ) )
 {
  std::cerr << "COM initialization failed" << std::endl;
  return -1;
 }

 // setup process-wide security context
 hr = CoInitializeSecurity( NULL, // we're not a server
          -1, // we're not a server
          NULL, // dito
          NULL, // reserved
          RPC_C_AUTHN_LEVEL_DEFAULT, // let DCOM decide
          RPC_C_IMP_LEVEL_IMPERSONATE,
          NULL,
          EOAC_NONE,
          NULL );
 if ( FAILED( hr ) )
 {
  std::cerr << "Security initialization failed" << std::endl;
  return -1;
 }

 // we're going to use CComPtr<>s, whose lifetime must end BEFORE CoUnitialize is called
 {
  // connect to WMI
  CComPtr< IWbemLocator > locator;
  hr = CoCreateInstance( CLSID_WbemAdministrativeLocator, NULL,
       CLSCTX_INPROC_SERVER,
       IID_IWbemLocator, reinterpret_cast< void** >( &locator ) );
  if ( FAILED( hr ) )
  {
   std::cerr << "Instantiation of IWbemLocator failed" << std::endl;
   return -1;
  }

      
  // connect to local service with current credentials
  CComPtr< IWbemServices > service;
  hr = locator->ConnectServer( L"root\\cimv2", NULL, NULL, NULL,
          WBEM_FLAG_CONNECT_USE_MAX_WAIT,
          NULL, NULL, &service );
   if ( SUCCEEDED( hr ) )
  {
     CComPtr< IEnumWbemClassObject > enumerator;
   hr = service->ExecQuery( L"WQL", L"SELECT * FROM Win32_computersystem",
             WBEM_FLAG_FORWARD_ONLY, NULL, &enumerator );
          
   if ( SUCCEEDED( hr ) )
   {
    CComPtr< IWbemClassObject > ptrInfo = NULL;
    ULONG retcnt;
    hr = enumerator->Next( WBEM_INFINITE, 1L, reinterpret_cast( &ptrInfo ), &retcnt );
    if ( SUCCEEDED( hr ) )
    {
     if ( retcnt > 0 )
     {
      
          _variant_t var_val;
             hr = ptrInfo->Get( L"Model", 0, &var_val, NULL, NULL );
              if ( SUCCEEDED( hr ) )
      {
       _bstr_t str = var_val;
                         
                           
       std::cout << str << std::endl;
      }
      else
      {
       std::cerr << "IWbemClassObject::Get failed" << std::endl;
       result = -1;
      }
     }
     else
     {
      std::cout << "Enumeration empty" << std::endl;
     }
    }
    else
    {
     std::cerr << "Error in iterating through enumeration" << std::cerr;
     result = -1;
    }
              
   }
   else
   {
    std::cerr << "Query failed" << std::endl;
    result = -1;
   }
  }
  else
  {
   std::cerr << "Couldn't connect to service" << std::endl;
   result = -1;
  }
       
 }
 CoUninitialize();

 return result;
}

 

你可能感兴趣的:(C++/MFC/STL,c++,null,initialization,instantiation,service,security)