WMI programming-receive Event Notifications

Source: Internet
Author: User

Receive Event Notifications (Wmi)

Srcurl: http://msdn2.microsoft.com/en-us/library/aa390425 (vs.85). aspx

The following sample code shows the process of COM Initialization, connecting to the local WMI, receiving events, and cleaning up. When a new process is created, the user will receive the. Event asynchronously.

Step 1-5 is the initial setup and connection to WMI, and step 6 is to receive events.
 

Process:

1. Call coinitializeex to initialize COM.

2. Call coinitializesecurity to initialize the com process security.
In Window 2000, you must specify sole_authentication_list in the pauthlist parameter of coinitializesecurity to set the default security authentication.

3. Call cocreateinstance to obtain the WMI Locator (Locator ).

4. Call iwbemlocator: connectserver and specify the strnetworkresource parameter as "root/cimv2". In this way, we can obtain a pointer to "iwbemservices.

5. Call cosetproxyblanket to set iwbemservices Proxy Security. In this way, WMI can simulate client roles.

6. use the iwbemservices: execnotificationqueryasync method to receive asynchronous events. to receive asynchronous events, we must implement iwbemobjectsink. the following code provides implementation in the eventsink class. when an event is received at any time, iwbemservices: execnotifqueryqueryasync calls eventsink: indicate. in this code example, when a process is created, eventsink: indicate is called.
Run the following code to open notepad.exe, and the notification event will be triggered.

# Include "eventsink. H"

Int main (INT iargcnt, char ** argv)
{
Hresult hres;

// Step 1 :--------------------------------------------------
// Initialize com .------------------------------------------

Hres = coinitializeex (0, coinit_multithreaded );
If (failed (hres ))
{
Cout <"failed to initialize com library. Error code = 0x"
<Hex Return 1; // program has failed.
}

// Step 2 :--------------------------------------------------
// Set general com security levels --------------------------
// Note: if you are using Windows 2000, you need to specify-
// The default authentication credentials for a user by using
// A sole_authentication_list structure in the pauthlist ----
// Parameter of coinitializesecurity ------------------------

Hres = coinitializesecurity (
Null,
-1, // com negotiates Service
Null, // authentication services
Null, // Reserved
Rpc_c_authn_level_default, // Default Authentication
Rpc_c_imp_level_impersonate, // default impersonation
Null, // authentication info
Eoac_none, // additional capabilities
Null // Reserved
);


If (failed (hres ))
{
Cout <"failed to initialize security. Error code = 0x"
<Hex Couninitialize ();
Return 1; // program has failed.
}

// Step 3 :---------------------------------------------------
// Obtain the initial locator to WMI -------------------------

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 Couninitialize ();
Return 1; // program has failed.
}

// Step 4 :---------------------------------------------------
// Connect to WMI through the iwbemlocator: connectserver Method

Iwbemservices * psvc = NULL;
 
// Connect to the local root/cimv2 namespace
// And obtain pointer psvc to make iwbemservices CILS.
Hres = ploc-> connectserver (
_ Bstr_t (L "root // cimv2 "),
Null,
Null,
0,
Null,
0,
0,
& Psvc
);

If (failed (hres ))
{
Cout <"cocould not connect. Error code = 0x"
<Hex Ploc-> release ();
Couninitialize ();
Return 1; // program has failed.
}

Cout <"connected to root // cimv2 WMI namespace" <Endl;

// Step 5 :--------------------------------------------------
// Set security levels on the proxy -------------------------

Hres = cosetproxyblanket (
Psvc, // indicates the proxy to set
Rpc_c_authn_winnt, // rpc_c_authn_xxx
Rpc_c_authz_none, // rpc_c_authz_xxx
Null, // server principal name
Rpc_c_authn_level_call, // rpc_c_authn_level_xxx
Rpc_c_imp_level_impersonate, // rpc_c_imp_level_xxx
Null, // client identity
Eoac_none // proxy capabilities
);

If (failed (hres ))
{
Cout <"cocould not set proxy blanket. Error code = 0x"
<Hex Psvc-> release ();
Ploc-> release ();
Couninitialize ();
Return 1; // program has failed.
}

// Step 6 :-------------------------------------------------
// Receive Event Notifications -----------------------------

// Use an unsecured apartment for security
Iunsecuredapartment * punsecapp = NULL; // The definitions of these pointers can use ccomqiptr or ccomptr to automatically manage the object lifecycle.

Hres = cocreateinstance (clsid_unsecuredapartment, null,
Clsctx_local_server, iid_iunsecuredapartment,
(Void **) & punsecapp );
 
Eventsink * psink = new eventsink;
Psink-> addref ();

Iunknown * pstubunk = NULL;
Punsecapp-> createobjectstub (psink, & pstubunk );

Iwbemobjectsink * pstubsink = NULL;
Pstubunk-> QueryInterface (iid_iwbemobjectsink,
(Void **) & pstubsink );

// The execnotificationqueryasync method will call
// The eventquery: Indicate method when an event occurs
Hres = psvc-> execicationicationqueryasync (
_ Bstr_t ("WQL "),
_ Bstr_t ("select *"
"From _ instancecreationevent within 1"
"Where targetinstance ISA 'win32 _ process '"),
Wbem_flag_send_status,
Null,
Pstubsink );

// Check for errors.
If (failed (hres ))
{
Printf ("execnotificationqueryasync failed"
"With = 0x % x/N", hres );
Psvc-> release ();
Ploc-> release ();
Punsecapp-> release ();
Pstubunk-> release ();
Psink-> release ();
Pstubsink-> release ();
Couninitialize ();
Return 1;
}

// Wait for the event
Sleep (10000 );

Hres = psvc-> cancelasynccall (pstubsink );

// Cleanup
// ==========

Psvc-> release ();
Ploc-> release ();
Punsecapp-> release ();
Pstubunk-> release ();
Psink-> release ();
Pstubsink-> release ();
Couninitialize ();

Return 0; // program successfully completed.
 
}

// ------------------------------------ Eventsink. h --------------------------------------------------//

# Ifndef eventsink_h
# Define eventsink_h

# DEFINE _ win32_dcom
# Include <iostream>
Using namespace STD;
# Include <comdef. h>
# Include <wbemidl. h>

# Pragma comment (Lib, "wbemuuid. lib ")

Class eventsink: Public iwbemobjectsink
{
Long m_lref;
Bool bdone;

Public:
Eventsink () {m_lref = 0 ;}
~ Eventsink () {bdone = true ;}

Virtual ulong stdmethodcalltype addref ();
Virtual ulong stdmethodcalltype release ();
Virtual hresult
Stdmethodcalltype QueryInterface (refiid riid, void ** GMM );

Virtual hresult stdmethodcalltype indicate (
Long lobjectcount,
Iwbemclassobject _ rpc_far * apobjarray
);

Virtual hresult stdmethodcalltype setstatus (
/* [In] */long lflags,
/* [In] */hresult,
/* [In] */BSTR strparam,
/* [In] */iwbemclassobject _ rpc_far * pobjparam
);
};

# Endif

// ------------------------------------------ Eventsink. cpp ------------------------------------------------//
//
# Include "eventsink. H"

Ulong eventsink: addref ()
{
Return interlockedincrement (& m_lref );
}

Ulong eventsink: release ()
{
Long lref = interlockeddecrement (& m_lref );
If (lref = 0)
Delete this;
Return lref;
}

Hresult eventsink: QueryInterface (refiid riid, void ** GMM)
{
If (riid = iid_iunknown | riid = iid_iwbemobjectsink)
{
* GMM = (iwbemobjectsink *) This;
Addref ();
Return wbem_s_no_error;
}
Else return e_nointerface;
}

Hresult eventsink: Indicate (long lobjectcount,
Iwbemclassobject ** apobjarray)
{
Hresult hres = s_ OK;

For (INT I = 0; I <lobjectcount; I ++)
{
Printf ("event occurred/N ");
}

Return wbem_s_no_error;
}

Hresult eventsink: setstatus (
/* [In] */long lflags,
/* [In] */hresult,
/* [In] */BSTR strparam,
/* [In] */iwbemclassobject _ rpc_far * pobjparam
)
{
If (lflags = wbem_status_complete)
{
Printf ("Call complete. hresult = 0x % x/N", hresult );
}
Else if (lflags = wbem_status_progress)
{
Printf ("call in progress./N ");
}

Return wbem_s_no_error;
} // End of eventsink. cpp

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.