Click to Rate and Give Feedback
MSDN
MSDN Library
Using WMI
 Creating a Connection to a WMI Name...

  Switch on low bandwidth view
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.

Aa389749.wedge(en-us,VS.85).gifTo create a connection to a WMI namespace

  1. 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.
        }
  2. 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"), 
                NULL, NULL, 0, NULL, 0, 0, &pSvc);
    
        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.

See Also

Creating a WMI Application Using C++
IPv6 and IPv4 Support in WMI

Send comments about this topic to Microsoft

Build date: 6/15/2009

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker