Bewerken

Delen via


Creating a Connection to a WMI Namespace

After you have set the standard calls to COM, you must then connect to WMI through a call to the IWbemLocator::ConnectServer method. The ConnectServer method returns a proxy of an IWbemServices interface. Through IWbemServices, you can access the different capabilities of WMI.

The code examples in this topic require the following references and #include statements to compile correctly.

#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <windows.h>
#include <wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")

The following procedure describes how to create a connection to a WMI namespace.

To create a connection to a WMI namespace

  • Initialize the IWbemLocator interface through a call to CoCreateInstance.

    WMI does not require that you perform any additional procedures when calling CoCreateInstance on IWbemLocator.

    The following code example describes how to initialize IWbemLocator.

        IWbemLocator *pLoc = 0;
        HRESULT hr;
    
        hr = CoCreateInstance(CLSID_WbemLocator, 0, 
            CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);
    
        if (FAILED(hr))
        {
            cout << "Failed to create IWbemLocator object. Err code = 0x"
                 << hex << hr << endl;
            CoUninitialize();
            return hr;     // Program has failed.
        }
    
    • Connect to WMI through a call to the IWbemLocator::ConnectServer method.

      The ConnectServer method returns a proxy to an IWbemServices interface that use to access the local or remote WMI namespace specified in your call to ConnectServer.

      The following code example describes how to call ConnectServer.

      IWbemServices *pSvc = 0;
      
          // Connect to the root\default namespace with the current user.
          hr = pLoc->ConnectServer(
                  BSTR(L"ROOT\\DEFAULT"),  //namespace
                  NULL,       // User name 
                  NULL,       // User password
                  0,         // Locale 
                  NULL,     // Security flags
                  0,         // Authority 
                  0,        // Context object 
                  &pSvc);   // IWbemServices proxy
      
      
          if (FAILED(hr))
          {
              cout << "Could not connect. Error code = 0x" 
                   << hex << hr << endl;
              pLoc->Release();
              CoUninitialize();
              return hr;      // Program has failed.
          }
      
          cout << "Connected to WMI" << endl;
      

After you have received a pointer to the IWbemServices proxy, you must set the security on the proxy to access WMI. For more information, see Setting the Security Levels on a WMI Connection.

Creating a WMI Application Using C++

IPv6 and IPv4 Support in WMI