[CPP]View PlainCopy
- #include "stdafx.h"
- #define _win32_dcom
- #include <iostream>
- Using namespace std;
- #include <comdef.h>
- #include <Wbemidl.h>
- # pragma comment (lib, "Wbemuuid.lib")
- int main (int argc, char **argv)
- {
- HRESULT hres;
- hres = CoInitializeEx (0, coinit_multithreaded);
- if (FAILED (hres))
- {
- cout << "Failed to initialize COM library."
- << "Error code = 0x"
- << hex << hres << Endl;
- return 1;
- }
- 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;
- return HR; //program has failed.
- }
- IWbemServices *psvc = 0;
- bstr_t Strnetworkresource ("root\\cimv2");
- hr = Ploc->connectserver (
- Strnetworkresource,
- 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;
- //Set the proxy so that impersonation of the client occurs.
- hr = 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 (HR))
- {
- cout << "Could not set proxy blanket. Error code = 0x "
- << hex << hr << Endl;
- Psvc->release ();
- Ploc->release ();
- CoUninitialize ();
- return HR;
- }
- bstr_t Strlang ("WQL");
- //monitor Taskmgr.exe process creation
- bstr_t strquery ("SELECT * from __InstanceCreationEvent within 1 WHERE targetinstance ISA ' Win32_Process ' and targetins Tance. Name = ' Taskmgr.exe ');
- ienumwbemclassobject* PResult = NULL;
- hr = Psvc->execnotificationquery (Strlang, strquery, Wbem_flag_forward_only | wbem_flag_return_immediately, NULL, &presult);
- if (SUCCEEDED (HR))
- {
- do{
- iwbemclassobject* pobject = NULL;
- ULONG lcnt = 0;
- hr = Presult->next (wbem_infinite, 1, &pobject, &lcnt);
- if (SUCCEEDED (HR) && pobject)
- {
- cout<<"Taskmgr.exe process created" <<endl;
- Break ; //Exit
- }
- }while (true);
- }
- Psvc->release ();
- Ploc->release ();
- CoUninitialize ();
- CoUninitialize ();
- return 0; //program successfully completed.
- }
http://blog.csdn.net/zwfgdlc/article/details/6613605
Using WMI to monitor process creation (VC version) under Ring3