WMI detect process creation event - c++ - c++

I am trying to create a notify event program when some specific process opens. I follow this post, and it works. I can get event when notepad.exe or powerpoint process opened.
However the program just execute one time, after the first notepad opened, the program stop checking new notepad process.
I know I may need a loop, but where should I add the loop?
Another question is that I check two type of process(notepad & powerpoint), so no matter which process opened, the event will be trigger. Is it possible to know which process trigger the function?
Suppose I open notepad, and I can know notepad process trigger event, not powerpoint
Main.cpp
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>
#include <atlcomcli.h>
#pragma comment(lib, "wbemuuid.lib")
#include "CreationEvent.h"
class EventSink : public IWbemObjectSink {
friend void CreationEvent::registerCreationCallback(TNotificationFunc callback);
CComPtr<IWbemServices> pSvc;
CComPtr<IWbemObjectSink> pStubSink;
LONG m_IRef;
CreationEvent::TNotificationFunc m_callback;
public:
EventSink(CreationEvent::TNotificationFunc callback) :m_IRef(0), m_callback(callback){}
~EventSink(){
}
virtual ULONG STDMETHODCALLTYPE AddRef() {
return InterlockedIncrement(&m_IRef);
}
virtual ULONG STDMETHODCALLTYPE Release() {
LONG IRef = InterlockedDecrement(&m_IRef);
if (IRef == 0)
delete this;
return IRef;
}
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) {
if (riid == IID_IUnknown || riid == IID_IWbemObjectSink) {
*ppv = (IWbemObjectSink*) this;
AddRef();
return WBEM_S_NO_ERROR;
}
else return E_NOINTERFACE;
}
virtual HRESULT STDMETHODCALLTYPE Indicate(
LONG lObjectCount,
IWbemClassObject __RPC_FAR *__RPC_FAR *apObjArray
){
m_callback();
/* Unregister event sink */
pSvc->CancelAsyncCall(pStubSink);
return WBEM_S_NO_ERROR;
}
virtual HRESULT STDMETHODCALLTYPE SetStatus(LONG IFlags, HRESULT hResult, BSTR strParam, IWbemClassObject __RPC_FAR *pObjParam) {
return WBEM_S_NO_ERROR;
}
};
void CreationEvent::registerCreationCallback(TNotificationFunc callback) {
CComPtr<IWbemLocator> pLoc;
CoInitializeEx(0, COINIT_MULTITHREADED);
HRESULT 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 << hres << endl;
throw std::exception("CreationEvent initialization failed");
}
CComPtr<EventSink> pSink(new EventSink(callback));
hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSink->pSvc);
if (FAILED(hres)) {
cout << "Could not connect. Error code = 0x" << hex << hres << endl;
throw std::exception("CreationEvent initialization failed");
}
hres = CoSetProxyBlanket(pSink->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(hres)) {
cout << "Coult not set proxy blanket, Error code =0x" << hex << hres << endl;
throw std::exception("CreationEvent initialization failed");
}
CComPtr<IUnsecuredApartment> pUnsecApp;
hres = CoCreateInstance(CLSID_UnsecuredApartment, NULL, CLSCTX_LOCAL_SERVER, IID_IUnsecuredApartment, (void**)&pUnsecApp);
CComPtr<IUnknown> pStubUnk;
pUnsecApp->CreateObjectStub(pSink, &pStubUnk);
pStubUnk->QueryInterface(IID_IWbemObjectSink, (void**)&pSink->pStubSink);
char buffer[512];
sprintf_s(buffer, "SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process' AND (TargetInstance.Name = 'Notepad.exe' OR TargetInstance.Name = 'Powerpnt.exe')");
hres = pSink->pSvc->ExecNotificationQueryAsync(_bstr_t("WQL"), _bstr_t(buffer), WBEM_FLAG_SEND_STATUS, NULL, pSink->pStubSink);
if (FAILED(hres)) {
cout << "ExecNotificationQueryAsync failed with = 0x" << hex << hres << endl;
throw std::exception("CreationEvent initialization failed");
}
}
void k() { cout << "process open" << endl; }
int main() {
CreationEvent::registerCreationCallback(k);
CoUninitialize();
}
Header.h
#pragma once
#ifndef _Header_h__
#define _Header_h__
#include <boost/function.hpp>
namespace CreationEvent {
typedef boost::function<void(void)> TNotificationFunc;
void registerCreationCallback(TNotificationFunc callback);
}
#endif

you should add a loop after the call to the ExecNotificationQueryAsyncat the end of the function registerCreationCallback, it can be a forever loop with done condition or you can use a WaitForSingleObject, then create an event and signaled when you want to finish your process, also you should release all the resources allocated.
For get the name of the process started, go to the Indicate function and change this
virtual HRESULT STDMETHODCALLTYPE Indicate(
LONG lObjectCount,
IWbemClassObject __RPC_FAR *__RPC_FAR *apObjArray
){
for (int i = 0; i < lObjectCount; i++){
_variant_t vtProp;
_variant_t cn;
hr = apObjArray[i]->Get(_bstr_t(L"TargetInstance"), 0, &vtProp, 0, 0)
IUnknown* str = vtProp;
HRESULT hr = str->QueryInterface(IID_IWbemClassObject, reinterpret_cast<void**>(&apObjArray[i]));
if (SUCCEEDED(hr))
{
_variant_t cn;
hr = apObjArray[i]->Get(L"Name", 0, &cn, NULL, NULL);
//here is the name of the process
//cn.bstrVal
m_callback();
}
}
/* Unregister event sink */
//you should not unregister the event if you want to receive more notifications, do this after
//your forever loop in registerCreationCallback
//pSvc->CancelAsyncCall(pStubSink);
return WBEM_S_NO_ERROR;
}
then you can send de name as a paremeter to your callback

Related

URLdownloadToFileW Doesn't download a file [duplicate]

I'm new to c++ and try to write a update function.
The download with URLDownloadToFile is working without problems but if I changed the url to an invalid one, it stilled return S_OK ... How can I check if the download succede or not?
#include <WinInet.h>
#include <iomanip>
int download_file (const TCHAR urldownload[],const TCHAR target[] )
{
DownloadProgress progress;
IBindStatusCallback* callback = (IBindStatusCallback*)&progress;
SCP(40, NULL); cout << target;
HRESULT status = URLDownloadToFile(NULL, urldownload, target, 0, static_cast<IBindStatusCallback*>(&progress));
Sleep(200);
DeleteUrlCacheEntry(urldownload);
wcout << status;
if (status == S_OK) cout << "yes";
else(cout << "Download failed");
Sleep(10000); return 1;
}
class DownloadProgress : public IBindStatusCallback {
public:
HRESULT __stdcall QueryInterface(const IID &, void **) {
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef(void) {
return 1;
}
ULONG STDMETHODCALLTYPE Release(void) {
return 1;
}
HRESULT STDMETHODCALLTYPE OnStartBinding(DWORD dwReserved, IBinding *pib) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetPriority(LONG *pnPriority) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnLowResource(DWORD reserved) {
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE OnStopBinding(HRESULT hresult, LPCWSTR szError) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetBindInfo(DWORD *grfBINDF, BINDINFO *pbindinfo) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC *pformatetc, STGMEDIUM *pstgmed) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(REFIID riid, IUnknown *punk) {
return E_NOTIMPL;
}
virtual HRESULT __stdcall OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText)
{
//wcout << ulProgress << L" of " << ulProgressMax << endl; Sleep(200);
if (ulProgress != 0 && ulProgressMax != 0)
{
double output = (double(ulProgress) / ulProgressMax)*100;
cout << "\r" << "Downloading: " << fixed << setprecision(2) << output << " % " ; Sleep(20);
}
return S_OK;
}
};
MSDN article has the answer for you:
URLDownloadToFile returns S_OK even if the file cannot be created and the download is canceled. If the szFileName parameter contains a file path, ensure that the destination directory exists before calling URLDownloadToFile. For best control over the download and its progress, an IBindStatusCallback interface is recommended.
You need to provide a status callback to receive status of the asynchronous operation. Your code snippet already has the base. OnProgress and OnStopBinding should get you the download failure result.

C++ check if web browser closed

#include <windows.h>
#include <exdisp.h>
class CWebBrowser{
public:
HRESULT hr;
IWebBrowserApp *www;
HRESULT init(){
CLSID clsid;
const IID IID_IEApplication = {0x0002DF05,0x0000,0x0000,{0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}};
if(www) hr = www->put_Visible(-1);
if(hr!=0 || www==NULL){
QuitBrowser();
hr=CLSIDFromProgID(L"InternetExplorer.Application",&clsid);
if(hr==0) hr=CoCreateInstance(clsid,NULL,CLSCTX_ALL,IID_IEApplication,reinterpret_cast<void**>(&www));
if(hr==0) hr = www->put_Visible(-1);
}
return hr;
}
HRESULT browse(BSTR addr){
VARIANT vEmpty;
VariantInit(&vEmpty);
hr=www->Navigate(addr, &vEmpty, &vEmpty, &vEmpty, &vEmpty);
VariantClear(&vEmpty);
return hr;
}
void QuitBrowser(){
if(www){
www->Quit();
www->Release();
www=NULL;
}
}
CWebBrowser(){
hr=CoInitialize(NULL);
}
~CWebBrowser(){
if(www){
www->Quit();
www->Release();
www=NULL;
}
CoUninitialize();
}
};
I am calling the init() function to check if Web Browser is still open before browse() another webpage.
When I run the app the first time there are 2 processes showing in Task Manager (iexplorer.exe) & (iexplorer.exe *32)
When I close the app sometimes processes close and sometimes they don't.
Sometimes (iexplorer.exe *32) closes and only (iexplorer.exe) is open. When I try calling init() in this case the app crashes.
Using CodeBlocks 17.12, Windows 2000 & IE 11.
This works fine for me. Maybe you are calling www->Release() prematurely.
Here is my MCVE:
#include <Windows.h>
#include <assert.h>
#include <Exdisp.h>
#include <iostream>
#pragma comment (lib, "SHDOCVW.lib")
IWebBrowserApp *www;
HRESULT init()
{
CLSID clsid;
const IID IID_IEApplication = {0x0002DF05,0x0000,0x0000,{0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}};
HRESULT hr = CLSIDFromProgID (L"InternetExplorer.Application", &clsid);
if (hr)
{
std::cout << std::hex << "CLSIDFromProgID failed, error " << hr << "\n";
return hr;
}
hr = CoCreateInstance (clsid, NULL, CLSCTX_ALL, IID_IEApplication, reinterpret_cast<void**>(&www));
if (hr)
{
std::cout << std::hex << "CoCreateInstance failed, error " << hr << "\n";
return hr;
}
hr = www->put_Visible(-1);
if (hr)
{
std::cout << std::hex << "put_Visible failed, error " << hr << "\n";
www->Release ();
www = nullptr;
return hr;
}
return S_OK;
}
HRESULT browse(BSTR addr)
{
HRESULT hr;
if (www)
{
VARIANT vEmpty;
VariantInit (&vEmpty);
hr = www->Navigate (addr, &vEmpty, &vEmpty, &vEmpty, &vEmpty);
VariantClear (&vEmpty);
}
return hr;
}
int main ()
{
HRESULT hr = CoInitializeEx (NULL, COINIT_APARTMENTTHREADED);
assert (hr == 0);
int mb_result;
while (1)
{
hr = init ();
if (hr == 0)
{
mb_result = MessageBoxW (NULL, L"About to browse", L"Browser Test", MB_OKCANCEL);
if (mb_result == IDOK)
{
BSTR url = SysAllocString (L"https://www.google.com");
hr = browse (url);
SysFreeString (url);
if (hr)
std::cout << "browse () returned: " << std::hex << hr << "\n";
}
mb_result = MessageBoxW (NULL, L"About to quit", L"Browser Test", MB_OKCANCEL);
if (mb_result == IDOK)
www->Quit ();
www->Release ();
www = nullptr;
}
mb_result = MessageBoxW (NULL, L"Again?", L"Browser Test", MB_YESNO);
if (mb_result == IDNO)
break;
}
CoUninitialize ();
}
And if I close the browser (Edge, in my case, running on Windows 10) between the calls to init and browse I get:
browse () returned: 800706ba
which is entirely understandable, since this error means "The RPC server unavailable". It certainly doesn't crash.
Edit
Stupid Vista bugs, see the OP's recent comments. After calling www->Quit() the next call to CoCreateInstance() fails, if you're too quick about it at least.
So, two suggestions.
1 (might work):
for (int i = 0; i < 10; ++i)
{
hr = CoCreateInstance (clsid, NULL, CLSCTX_ALL, IID_IEApplication, reinterpret_cast<void**>(&www));
if (hr != ERROR_SHUTDOWN_IS_SCHEDULED) // not really
break;
Sleep (1000);
}
2 (a bit more drastic, error handling omitted for brevity):
// www->Quit ();
HWND hWnd;
hr = www->get_HWND ((SHANDLE_PTR *) &hWnd);
if (hr == S_OK)
{
DWORD processID;
if (GetWindowThreadProcessId (hWnd, &processID))
{
HANDLE hProcess = OpenProcess (PROCESS_TERMINATE, FALSE, processID);
if (hProcess)
{
TerminateProcess (hProcess, (DWORD) -1);
CloseHandle (hProcess);
}
}
}
Want to give it a try, OP, and report back?

DirectShow Filter Rejection using IAMGraphBuilderCallBack

I've been attempting to implement IAMGraphBuilderCallback interface
I would imagine that the callback gets called everytime a candidate filter is found through intelligent-connect, but the call back in my impelmentation only gets called once during graph construction regardless of if I accept or reject the filter, which I'm not sure why.
I've used grapheditNext.exe to view the default setup when constructing the graph, which uses both the Microsoft DTV Video and Audio decoder.
(Graph without callBack)
I've implemented the Select Filter Method to reject both of the filter.
(Graph with callBack)
Lav Video filter was inserted when viewed using grapheditNext remote graph and the select filter callback never gets called after. This behaviour brings me to conclude two problems with my current implementation.
even though multiple filters are inserted by intelligent connect (DTV Video and DTV Audio), the callback is only called once.
even when you reject the filter in a callback, the callback is not called for other filters that are proposed/inserted.
Update:
I've implemented manual connection method to Connect two filter. I've inserted a source filter, mp4 demux filter, video renderer and audio renderer. The connection sequence and its behavior is as follows:
Source Filter -> mp4 Demux (Direct Connect)
mp4 Demux -> Video Renderer
Callback happened once. Microsoft DTV video decoder was rejected with the callback. Lav filter was inserted after without triggering the callback.
mp4 Demux -> Audio Renderer
Microsoft DTV audio decoder was inserted without the callback.
The little test app I've wrote is as follows:
#include <iostream>
#include <dshow.h>
#include <Streams.h>
#include <Combase.h>
#include <vector>
#include <algorithm>
void insertCallBackHandle(IGraphBuilder* pGraph, IAMGraphBuilderCallback* pGraphBuilderCallBackWithExcluList);
class GraphBuilderCallBackWithExcluList : public IAMGraphBuilderCallback, public CUnknown
{
public:
DECLARE_IUNKNOWN
GraphBuilderCallBackWithExcluList()
: CUnknown(NAME("GraphBuilderCallback"), NULL)
{
}
virtual HRESULT STDMETHODCALLTYPE SelectedFilter(
/* [in] */ IMoniker *pMon);
{
GUID DTVVideo = { 0x212690FB, 0x83E5, 0x4526,{ 0x8F, 0xD7, 0x74, 0x47, 0x8B, 0x79, 0x39, 0xCD } };
GUID DTVAudio = { 0xE1F1A0B8, 0xBEEE, 0x490D,{ 0xBA, 0x7C, 0x06, 0x6C, 0x40, 0xB5, 0xE2, 0xB9 } };
std::vector<GUID> m_vFilterGuid;
m_vFilterGuid.push_back(DTVVideo);
m_vFilterGuid.push_back(DTVAudio);
IPropertyBag *pPropBag;
HRESULT hr = pMon->BindToStorage(0, 0, IID_IPropertyBag,
(void **)&pPropBag);
if (SUCCEEDED(hr))
{
VARIANT varName;
VariantInit(&varName);
hr = pPropBag->Read(L"CLSID", &varName, 0);
if (SUCCEEDED(hr))
{
LPCWSTR name = varName.bstrVal ? varName.bstrVal : L"";
GUID classIdOfFilter;;
HRESULT hr = CLSIDFromString(name,(LPCLSID)&classIdOfFilter);
if (SUCCEEDED(hr))
{
auto it = std::find_if(m_vFilterGuid.begin(), m_vFilterGuid.end(), [&classIdOfFilter](const GUID excluFilter) {return excluFilter == classIdOfFilter; });
if (it == m_vFilterGuid.end())
{
VariantClear(&varName);
pPropBag->Release();
return S_OK;
}
else
{
VariantClear(&varName);
pPropBag->Release();
return E_FAIL;
}
}
else
{
VariantClear(&varName);
pPropBag->Release();
return E_FAIL;
}
}
else
{
VariantClear(&varName);
pPropBag->Release();
return E_FAIL;
}
}
else
{
pPropBag->Release();
return E_FAIL;
}
}
virtual HRESULT STDMETHODCALLTYPE CreatedFilter(
/* [in] */ IBaseFilter *pFil)
{
return S_OK;
}
STDMETHOD(NonDelegatingQueryInterface)(REFIID iid, void** ppv)
{
if (iid == __uuidof(IAMGraphBuilderCallback))
return GetInterface((IAMGraphBuilderCallback*)this, ppv);
return CUnknown::NonDelegatingQueryInterface(iid, ppv);
}
};
int main()
{
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr))
{
std::cout << "Failed to initialise directshow";
}
GraphBuilderCallBackWithExcluList* pGraphBuilderCallBackWithExcluList = new GraphBuilderCallBackWithExcluList;
IGraphBuilder *pGraph;
hr = CoCreateInstance(CLSID_FilterGraph, NULL,
CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&pGraph);
if (FAILED(hr))
{
std::cout << "Failed to create filter graph instance";
}
IMediaControl *pControl;
IMediaEvent *pEvent;
hr = pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
if (FAILED(hr))
{
std::cout << "Failed to query interface media control";
}
hr = pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);
if (FAILED(hr))
{
std::cout << "Failed to query interface media event";
}
insertCallBackHandle(pGraph, pGraphBuilderCallBackWithExcluList);
IBaseFilter * pFilter0 = NULL;
GUID fileSource = { 0xE436EBB5 ,0x524F ,0x11CE, { 0x9F,0x53, 0x00,0x20,0xAF, 0x0B, 0xA7, 0x70} };
hr = CoCreateInstance(fileSource, NULL, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&pFilter0));
if (FAILED(hr))
{
std::cout << "Failed to create mp4Demux filter";
}
IFileSourceFilter * pFilterSourceFitler;
hr = pFilter0->QueryInterface(&pFilterSourceFitler);
if (FAILED(hr))
{
std::cout << "Failed to query interface IFileSourceFilter";
}
LPCOLESTR FileSourceUri = L"D:\\Test.mp4";
hr = pFilterSourceFitler->Load(FileSourceUri, NULL);
if (FAILED(hr))
{
std::cout << "Failed to load fileSource uri";
}
IBaseFilter * pFilter1 = NULL;
GUID mp4Demux = { 0x025BE2E4 , 0x1787 , 0x4DA4,{ 0xA5, 0x85, 0xC5,0xB2,0xB9,0xEE,0xB5,0x7C } };
hr = CoCreateInstance(mp4Demux, NULL, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&pFilter1));
if (FAILED(hr))
{
std::cout << "Failed to create mp4Demux filter";
}
IBaseFilter * pFilter2 = NULL;
GUID videoRenderer = { 0xB87BEB7B , 0x8D29 , 0x423F, { 0xAE, 0x4D, 0x65,0x82,0xC1,0x01,0x75,0xAC }};
hr = CoCreateInstance(videoRenderer, NULL, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&pFilter2));
if (FAILED(hr))
{
std::cout << "Failed to create videoRenderer filter";
}
IBaseFilter * pFilter3 = NULL;
GUID audioRenderer = { 0x79376820 , 0x07D0 ,0x11CF, {0xA2,0x4D,0x00,0x20,0xAF,0xD7,0x97,0x67} };
hr = CoCreateInstance(audioRenderer, NULL, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&pFilter3));
if (FAILED(hr))
{
std::cout << "Failed to create audioRenderer filter";
}
hr = pGraph->AddFilter(pFilter0, NULL);
if (FAILED(hr))
{
std::cout << "Failed to add mp4Demux filter";
}
hr = pGraph->AddFilter(pFilter1, NULL);
if (FAILED(hr))
{
std::cout << "Failed to add mp4Demux filter";
}
hr = pGraph->AddFilter(pFilter2, NULL);
if (FAILED(hr))
{
std::cout << "Failed to add videoRenderer filter";
}
hr = pGraph->AddFilter(pFilter3, NULL);
if (FAILED(hr))
{
std::cout << "Failed to add audioRenderer filter";
}
// Auto connect
// Connect FileSource to mp4Demux
hr = ConnectFilters(pGraph, pFilter0, pFilter1);
if (FAILED(hr))
{
std::cout << "Failed to connect FilterSource to mp4Demux" << hr;
}
// Connect mp4Demux to Video Renderer
hr = ConnectFilters(pGraph, pFilter1, pFilter2);
if (FAILED(hr))
{
std::cout << "Failed to connect mp4Demux to videoRenderer";
}
// Connect mp4Demux to Audio Renderer
hr = ConnectFilters(pGraph, pFilter1, pFilter3);
if (FAILED(hr))
{
std::cout << "Failed to connect mp4Demux to audioRenderer";
}
hr = pControl->Run();
if (FAILED(hr))
{
std::cout << "Failed to run graph";
}
long evCode = 0;
pEvent->WaitForCompletion(INFINITE, &evCode);
pControl->Release();
pEvent->Release();
pGraph->Release();
CoUninitialize();
return 0;
}
void insertCallBackHandle(IGraphBuilder* pGraph,IAMGraphBuilderCallback* pGraphBuilderCallBackWithExcluList)
{
IObjectWithSite* iObjectWithSite;
HRESULT hr = pGraph->QueryInterface(&iObjectWithSite);
if (FAILED(hr))
{
std::cout << "Failed to query interface iObjectWithSite";
}
hr = iObjectWithSite->SetSite(pGraphBuilderCallBackWithExcluList);
if (FAILED(hr))
{
std::cout << "Failed to set site";
}
if (iObjectWithSite)
{
iObjectWithSite->Release();
}
}
So i missed the crucial point in COM implementation on reference count. The problem with the above implementation is that the reference count of the IAMGraphBuilderCallback Object is always zero, so the callback was called once and possibly destroyed after by directshow because of 0 reference count and never gets called again. With the above implementation, the work around I came up with is to manually increment the reference count when creating the object
GraphBuilderCallBackWithExcluList* pGraphBuilderCallBackWithExcluList = new GraphBuilderCallBackWithExcluList;
pGraphBuilderCallBackWithExcluList->NonDelegatingAddRef()
and calling
pGraphBuilderCallBackWithExcluList->NonDelegatingRelease()
Alternatively I found the code to fake the reference count with the following implementation:
class GraphBuilderCallBackWithExcluList : public IAMGraphBuilderCallback
{
public:
GraphBuilderCallBackWithExcluList()
{
}
virtual HRESULT STDMETHODCALLTYPE SelectedFilter(
/* [in] */ IMoniker *pMon)
{
GUID DTVVideo = { 0x212690FB, 0x83E5, 0x4526,{ 0x8F, 0xD7, 0x74, 0x47, 0x8B, 0x79, 0x39, 0xCD } };
GUID DTVAudio = { 0xE1F1A0B8, 0xBEEE, 0x490D,{ 0xBA, 0x7C, 0x06, 0x6C, 0x40, 0xB5, 0xE2, 0xB9 } };
std::vector<GUID> m_vFilterGuid;
m_vFilterGuid.push_back(DTVVideo);
m_vFilterGuid.push_back(DTVAudio);
IPropertyBag *pPropBag;
HRESULT hr = pMon->BindToStorage(0, 0, IID_IPropertyBag,
(void **)&pPropBag);
if (SUCCEEDED(hr))
{
VARIANT varName;
VariantInit(&varName);
hr = pPropBag->Read(L"CLSID", &varName, 0);
if (SUCCEEDED(hr))
{
LPCWSTR name = varName.bstrVal ? varName.bstrVal : L"";
GUID classIdOfFilter;;
HRESULT hr = CLSIDFromString(name, (LPCLSID)&classIdOfFilter);
if (SUCCEEDED(hr))
{
auto it = std::find_if(m_vFilterGuid.begin(), m_vFilterGuid.end(), [&classIdOfFilter](const GUID excluFilter) {return excluFilter == classIdOfFilter; });
if (it == m_vFilterGuid.end())
{
VariantClear(&varName);
pPropBag->Release();
return S_OK;
}
else
{
VariantClear(&varName);
pPropBag->Release();
return E_FAIL;
}
}
else
{
VariantClear(&varName);
pPropBag->Release();
return E_FAIL;
}
}
else
{
VariantClear(&varName);
pPropBag->Release();
return E_FAIL;
}
}
else
{
pPropBag->Release();
return E_FAIL;
}
}
virtual HRESULT STDMETHODCALLTYPE CreatedFilter(
/* [in] */ IBaseFilter *pFil)
{
return S_OK;
}
/**
* #brief Fake out any COM ref counting
*/
STDMETHODIMP_(ULONG) AddRef() { return 2; }
/**
* #brief Fake out any COM ref counting
*/
STDMETHODIMP_(ULONG) Release() { return 1; }
/**
* #brief Fake out any COM ref QI'ing
*/
STDMETHODIMP QueryInterface(REFIID riid, void ** ppv)
{
CheckPointer(ppv, E_POINTER);
if (riid == IID_IAMGraphBuilderCallback || riid == IID_IUnknown)
{
*ppv = (void *) static_cast<IAMGraphBuilderCallback*> (this);
return NOERROR;
}
return E_NOINTERFACE;
}
};

URLDownloadToFile always return S_OK

I'm new to c++ and try to write a update function.
The download with URLDownloadToFile is working without problems but if I changed the url to an invalid one, it stilled return S_OK ... How can I check if the download succede or not?
#include <WinInet.h>
#include <iomanip>
int download_file (const TCHAR urldownload[],const TCHAR target[] )
{
DownloadProgress progress;
IBindStatusCallback* callback = (IBindStatusCallback*)&progress;
SCP(40, NULL); cout << target;
HRESULT status = URLDownloadToFile(NULL, urldownload, target, 0, static_cast<IBindStatusCallback*>(&progress));
Sleep(200);
DeleteUrlCacheEntry(urldownload);
wcout << status;
if (status == S_OK) cout << "yes";
else(cout << "Download failed");
Sleep(10000); return 1;
}
class DownloadProgress : public IBindStatusCallback {
public:
HRESULT __stdcall QueryInterface(const IID &, void **) {
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef(void) {
return 1;
}
ULONG STDMETHODCALLTYPE Release(void) {
return 1;
}
HRESULT STDMETHODCALLTYPE OnStartBinding(DWORD dwReserved, IBinding *pib) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetPriority(LONG *pnPriority) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnLowResource(DWORD reserved) {
return S_OK;
}
virtual HRESULT STDMETHODCALLTYPE OnStopBinding(HRESULT hresult, LPCWSTR szError) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE GetBindInfo(DWORD *grfBINDF, BINDINFO *pbindinfo) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC *pformatetc, STGMEDIUM *pstgmed) {
return E_NOTIMPL;
}
virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(REFIID riid, IUnknown *punk) {
return E_NOTIMPL;
}
virtual HRESULT __stdcall OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText)
{
//wcout << ulProgress << L" of " << ulProgressMax << endl; Sleep(200);
if (ulProgress != 0 && ulProgressMax != 0)
{
double output = (double(ulProgress) / ulProgressMax)*100;
cout << "\r" << "Downloading: " << fixed << setprecision(2) << output << " % " ; Sleep(20);
}
return S_OK;
}
};
MSDN article has the answer for you:
URLDownloadToFile returns S_OK even if the file cannot be created and the download is canceled. If the szFileName parameter contains a file path, ensure that the destination directory exists before calling URLDownloadToFile. For best control over the download and its progress, an IBindStatusCallback interface is recommended.
You need to provide a status callback to receive status of the asynchronous operation. Your code snippet already has the base. OnProgress and OnStopBinding should get you the download failure result.

How to get a instance of Win32_SecurityDescriptor in WMI?

i'm writting a C++ WMI utility class which wraps the WMI stuff to help my further WMI query. i encountered a problem when accessing a Win32_SecurityDescriptor instance.
i used the WQL query "Select * from Win32_LogicalShareSecuritySetting" to get all the Win32_LogicalShareSecuritySetting instances. then called the GetSecurityDescriptor method of Win32_LogicalShareSecuritySetting instance to get a Win32_SecurityDescriptor instance. But when i attempted to retrieve some property like "__PATH" from the Win32_SecurityDescriptor instance, i got a 0xC0000005 Access Violation messagebox.
i wrote my code in C++, but i think the problem should be common.
I also used the wbemtest tool by Microsoft for test but didn't find a way to display a Win32_SecurityDescriptor instance. Why is Win32_SecurityDescriptor so special?
here's all my code, you can try it in your VC, mine is 6. Windows SDK maybe needed.
Access Violation found in the caller code:
CString strSDInstancePath = wmiSearcher->getStringFromObject(pSDInstance, "__PATH");
ADWMISearch.cpp
#include "StdAfx.h"
#include "ADWMISearch.h"
#include <comdef.h>
# pragma comment(lib, "wbemuuid.lib")
# pragma comment(lib, "credui.lib")
# pragma comment(lib, "comsupp.lib")
#include <wincred.h>
#include <strsafe.h>
#include <iostream>
using namespace std;
DWORD ADWMISearch::WIN32_FROM_HRESULT_alternate(HRESULT hr)
{
DWORD dwResult;
if (hr < 0)
{
dwResult = (DWORD) hr;
return dwResult;
}
else
{
MyMessageBox_Error(_T("WIN32_FROM_HRESULT_alternate Error."), _T("Error"));
return -1;
}
}
IWbemServices* ADWMISearch::connect(CString strServerName, CString strServerIP, CString strDomainName, CString strUsername,
CString strPassword)
{
CString strComputerName = strServerName;
CString strFullUsername; //_T("adtest\\Administrator")
if (strDomainName == _T(""))
{
strUsername = _T("");
strFullUsername = _T("");
strPassword = _T("");
}
else
{
strFullUsername = strDomainName + _T("\\") + strUsername;
}
HRESULT hres;
// Step 1: --------------------------------------------------
// Initialize COM. ------------------------------------------
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
//cout << "Failed to initialize COM library. Error code = 0x"
// << hex << hres << endl;
MyMessageBox_Error(_T("connect"));
return NULL; // Program has failed.
}
// Step 2: --------------------------------------------------
// Set general COM security levels --------------------------
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IDENTIFY, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL // Reserved
);
//char aaa[100];
//sprintf(aaa, "%x", hres);
if (FAILED(hres) && hres != RPC_E_TOO_LATE)
{
//cout << "Failed to initialize security. Error code = 0x"
// << hex << hres << endl;
CoUninitialize();
MyMessageBox_Error(_T("connect"));
return NULL; // 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))
{
CoUninitialize();
MyMessageBox_Error(_T("connect"));
return NULL; // Program has failed.
}
// Step 4: -----------------------------------------------------
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = NULL;
bool useToken = TRUE;
bool useNTLM = FALSE;
// Get the user name and password for the remote computer
/*
CREDUI_INFO cui;
bool useToken = TRUE;
bool useNTLM = FALSE;
TCHAR pszName[CREDUI_MAX_USERNAME_LENGTH+1] = {0};
TCHAR pszPwd[CREDUI_MAX_PASSWORD_LENGTH+1] = {0};
TCHAR pszDomain[CREDUI_MAX_USERNAME_LENGTH+1];
TCHAR pszUserName[CREDUI_MAX_USERNAME_LENGTH+1];
TCHAR pszAuthority[CREDUI_MAX_USERNAME_LENGTH+1];
BOOL fSave;
DWORD dwErr;
memset(&cui,0,sizeof(CREDUI_INFO));
cui.cbSize = sizeof(CREDUI_INFO);
cui.hwndParent = NULL;
// Ensure that MessageText and CaptionText identify
// what credentials to use and which application requires them.
cui.pszMessageText = _T("Press cancel to use process token");
cui.pszCaptionText = _T("Enter Account Information");
cui.hbmBanner = NULL;
fSave = FALSE;
dwErr = CredUIPromptForCredentials(
&cui, // CREDUI_INFO structure
_T(""), // Target for credentials
NULL, // Reserved
0, // Reason
pszName, // User name
CREDUI_MAX_USERNAME_LENGTH+1, // Max number for user name
pszPwd, // Password
CREDUI_MAX_PASSWORD_LENGTH+1, // Max number for password
&fSave, // State of save check box
CREDUI_FLAGS_GENERIC_CREDENTIALS |// flags
CREDUI_FLAGS_ALWAYS_SHOW_UI |
CREDUI_FLAGS_DO_NOT_PERSIST);
if(dwErr == ERROR_CANCELLED)
{
useToken = true;
}
else if (dwErr)
{
cout << "Did not get credentials " << dwErr << endl;
pLoc->Release();
CoUninitialize();
return 1;
}
*/
// change the computerName strings below to the full computer name
// of the remote computer
CString strAuthority;
if(!useNTLM)
{
//StringCchPrintf(pszAuthority, CREDUI_MAX_USERNAME_LENGTH+1, _T("kERBEROS:%s"), strComputerName);
strAuthority = _T("kERBEROS:") + strComputerName;
}
// Connect to the remote root\cimv2 namespace
// and obtain pointer pSvc to make IWbemServices calls.
//---------------------------------------------------------
CString strNetworkResource = _T("\\\\") + strComputerName + _T("\\root\\cimv2");
if (strFullUsername == _T(""))
{
hres = pLoc->ConnectServer(
_bstr_t(strNetworkResource),
NULL, // User name
NULL, // User password
NULL, // Locale
WBEM_FLAG_CONNECT_USE_MAX_WAIT, // Security flags
_bstr_t(strAuthority), // Authority
NULL, // Context object
&pSvc // IWbemServices proxy
);
}
else
{
hres = pLoc->ConnectServer(
_bstr_t(strNetworkResource),
_bstr_t(strFullUsername), // User name
_bstr_t(strPassword), // User password
NULL, // Locale
WBEM_FLAG_CONNECT_USE_MAX_WAIT, // Security flags
_bstr_t(strAuthority), // Authority
NULL, // Context object
&pSvc // IWbemServices proxy
);
}
if (FAILED(hres))
{
DWORD aaa = WIN32_FROM_HRESULT_alternate(hres);
//cout << "Could not connect. Error code = 0x"
// << hex << hres << endl;
pLoc->Release();
CoUninitialize();
MyMessageBox_Error(_T("connect"));
return NULL; // Program has failed.
}
//cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;
// step 5: --------------------------------------------------
// Create COAUTHIDENTITY that can be used for setting security on proxy
COAUTHIDENTITY *userAcct = NULL;
COAUTHIDENTITY authIdent;
if(!useToken)
{
memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
authIdent.PasswordLength = strPassword.GetLength();
authIdent.Password = (USHORT*) _bstr_t(strPassword);
authIdent.Domain = (USHORT*) _bstr_t(strDomainName);
authIdent.DomainLength = strDomainName.GetLength();
authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
userAcct = &authIdent;
}
// Step 6: --------------------------------------------------
// Set security levels on a WMI connection ------------------
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hres))
{
//cout << "Could not set proxy blanket. Error code = 0x"
// << hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
MyMessageBox_Error(_T("connect"));
return NULL; // Program has failed.
}
// Cleanup
// ========
pLoc->Release();
return pSvc;
}
vector<IWbemClassObject*> ADWMISearch::query(IWbemServices *pSvc, CString strDomainName, CString strPassword, CString strWQL)
{
vector<IWbemClassObject*> npResultObjects;
BOOL useToken = TRUE;
// step 5: --------------------------------------------------
// Create COAUTHIDENTITY that can be used for setting security on proxy
COAUTHIDENTITY *userAcct = NULL;
COAUTHIDENTITY authIdent;
if(!useToken)
{
memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
authIdent.PasswordLength = strPassword.GetLength();
authIdent.Password = (USHORT*) _bstr_t(strPassword);
/*
LPTSTR slash = _tcschr(pszName, _T('\\'));
if( slash == NULL )
{
//cout << _T("Could not create Auth identity. No domain specified\n") ;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1; // Program has failed.
}
StringCchCopy(pszUserName, CREDUI_MAX_USERNAME_LENGTH+1, slash+1);
authIdent.User = (USHORT*)pszUserName;
authIdent.UserLength = _tcslen(pszUserName);
StringCchCopyN(pszDomain, CREDUI_MAX_USERNAME_LENGTH+1, pszName, slash - pszName);
*/
authIdent.Domain = (USHORT*) _bstr_t(strDomainName);
authIdent.DomainLength = strDomainName.GetLength();
authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
userAcct = &authIdent;
}
// Step 7: --------------------------------------------------
// Use the IWbemServices pointer to make requests of WMI ----
// For example, get the name of the operating system
IEnumWbemClassObject* pEnumerator = NULL;
HRESULT hResult;
hResult = pSvc->ExecQuery(
_bstr_t(_T("WQL")),
_bstr_t(strWQL), //_T("Select * from Win32_Share")
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
if (FAILED(hResult))
{
//cout << "Query for operating system name failed."
// << " Error code = 0x"
// << hex << hres << endl;
MyMessageBox_Error(_T("query"));
return npResultObjects; // Program has failed.
}
// Step 8: -------------------------------------------------
// Secure the enumerator proxy
hResult = CoSetProxyBlanket(
pEnumerator, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hResult))
{
//cout << "Could not set proxy blanket on enumerator. Error code = 0x"
// << hex << hres << endl;
pEnumerator->Release();
MyMessageBox_Error(_T("query"));
return npResultObjects; // Program has failed.
}
// When you have finished using the credentials,
// erase them from memory.
// Step 9: -------------------------------------------------
// Get the data from the query in step 7 -------------------
IWbemClassObject *pclsObj = NULL;
ULONG uReturn = 0;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
&pclsObj, &uReturn);
if(0 == uReturn)
{
break;
}
npResultObjects.push_back(pclsObj);
/*
VARIANT vtProp;
// Get the value of the Name property
hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
cout << _T("OS Name: ") << vtProp.bstrVal << endl;
// Get the value of the FreePhysicalMemory property
hr = pclsObj->Get(L"FreePhysicalMemory", 0, &vtProp, 0, 0);
cout << "Free physical memory(in kilobytes): " << vtProp.uintVal << endl;
VariantClear(&vtProp);
pclsObj->Release();
pclsObj = NULL;
*/
}
// Cleanup
// ========
pEnumerator->Release();
return npResultObjects;
}
CString ADWMISearch::getStringFromObject(IWbemClassObject* pObject, CString strPropertyName)
{
_bstr_t bstrPropertyName = strPropertyName;
VARIANT vtProperty;
CString strProperty;
// Get the value of the property
VariantInit(&vtProperty);
HRESULT hResult = pObject->Get(bstrPropertyName, 0, &vtProperty, 0, 0);
if (SUCCEEDED(hResult) && V_VT(&vtProperty) == VT_BSTR)
{
strProperty = vtProperty.bstrVal;
VariantClear(&vtProperty);
return strProperty;
}
else
{
VariantClear(&vtProperty);
MyMessageBox_Error(_T("getStringsFromObjects"));
return _T("");
}
}
vector<CString> ADWMISearch::getStringsFromObjects(vector<IWbemClassObject*> npObjects, CString strPropertyName)
{
_bstr_t bstrPropertyName = strPropertyName;
vector<CString> nstrProperties;
for (int i = 0; i < npObjects.size(); i ++)
{
VARIANT vtProperty;
CString strProperty;
// Get the value of the property
VariantInit(&vtProperty);
HRESULT hResult = npObjects[i]->Get(bstrPropertyName, 0, &vtProperty, 0, 0);
if (SUCCEEDED(hResult) && V_VT(&vtProperty) == VT_BSTR)
{
CString strProperty = vtProperty.bstrVal;
nstrProperties.push_back(strProperty);
VariantClear(&vtProperty);
}
else
{
VariantClear(&vtProperty);
MyMessageBox_Error(_T("getStringsFromObjects"));
return nstrProperties;
}
}
return nstrProperties;
}
void ADWMISearch::clearObjects(vector<IWbemClassObject*> npObjects)
{
for (int i = 0; i < npObjects.size(); i ++)
{
npObjects[i]->Release();
npObjects[i] = NULL;
}
npObjects.clear();
}
IWbemClassObject* ADWMISearch::getWMIClass(IWbemServices *pSvc, CString strClassName)
{
HRESULT hResult;
IWbemClassObject* pClass = NULL;
hResult = pSvc->GetObject(_bstr_t(strClassName), 0, NULL, &pClass, NULL); //_T("Win32_Share")
if (!SUCCEEDED(hResult))
{
MyMessageBox_Error(_T("getWMIClass"));
return NULL;
}
else
{
return pClass;
}
}
IWbemClassObject* ADWMISearch::getObjectFromObject(IWbemClassObject *pObject, CString strArgumentName)
{
if (!pObject)
{
MyMessageBox_Error(_T("getObjectFromObject"));
return NULL;
}
HRESULT hResult;
VARIANT varArgument;
hResult = pObject->Get(_bstr_t(strArgumentName), 0, &varArgument, NULL, 0);
if (!SUCCEEDED(hResult))
{
VariantClear(&varArgument);
MyMessageBox_Error(_T("getObjectFromObject"));
return NULL;
}
//IWbemClassObject **ppResultObject;
IWbemClassObject *pResultObject2;
if (V_VT(&varArgument) == VT_UNKNOWN)
{
//ppResultObject = (IWbemClassObject **)varArgument.ppunkVal;
pResultObject2 = (IWbemClassObject *)varArgument.punkVal;
}
else if (V_VT(&varArgument) == VT_DISPATCH)
{
//ppResultObject = (IWbemClassObject **)varArgument.ppdispVal;
pResultObject2 = (IWbemClassObject *)varArgument.pdispVal;
}
else
{
VariantClear(&varArgument);
MyMessageBox_Error(_T("getObjectFromObject"));
return NULL;
}
VariantClear(&varArgument);
//IWbemClassObject *pResultObject = *ppResultObject;
//return pResultObject;
return pResultObject2;
}
IWbemClassObject* ADWMISearch::getObjectFromObjectWithCheck(IWbemClassObject *pOutParams, CString strArgumentName)
{
if (!pOutParams)
{
MyMessageBox_Error(_T("getObjectFromObjectWithCheck"));
return NULL;
}
HRESULT hResult;
VARIANT varReturnValue;
VARIANT varArgument;
hResult = pOutParams->Get(_bstr_t(L"ReturnValue"), 0, &varReturnValue, NULL, 0);
if (!SUCCEEDED(hResult))
{
VariantClear(&varReturnValue);
VariantClear(&varArgument);
MyMessageBox_Error(_T("getObjectFromObjectWithCheck"));
return NULL;
}
DWORD dwResult = varReturnValue.lVal;
hResult = pOutParams->Get(_bstr_t(strArgumentName), 0, &varArgument, NULL, 0);
if (!SUCCEEDED(hResult))
{
VariantClear(&varReturnValue);
VariantClear(&varArgument);
MyMessageBox_Error(_T("getObjectFromObjectWithCheck"));
return NULL;
}
//IWbemClassObject **ppResultObject;
IWbemClassObject *pResultObject2;
if (V_VT(&varArgument) == VT_UNKNOWN)
{
//ppResultObject = (IWbemClassObject **)varArgument.ppunkVal;
pResultObject2 = (IWbemClassObject *)varArgument.punkVal;
}
else if (V_VT(&varArgument) == VT_DISPATCH)
{
//ppResultObject = (IWbemClassObject **)varArgument.ppdispVal;
pResultObject2 = (IWbemClassObject *)varArgument.pdispVal;
}
else
{
VariantClear(&varReturnValue);
VariantClear(&varArgument);
MyMessageBox_Error(_T("getObjectFromObjectWithCheck"));
return NULL;
}
VariantClear(&varReturnValue);
VariantClear(&varArgument);
//IWbemClassObject *pResultObject = *ppResultObject;
//return pResultObject;
return pResultObject2;
}
vector<ADWMIParam> ADWMISearch::genObjectArguments(CString strArgName, IWbemClassObject *pObject)
{
vector<ADWMIParam> resultArgs;
resultArgs.push_back(ADWMIParam(strArgName, pObject));
return resultArgs;
}
IWbemClassObject* ADWMISearch::callStaticMethod(IWbemServices *pSvc, IWbemClassObject *pClass, CString strClassName,
CString strMethodName)
{
return callStaticMethod(pSvc, pClass, strClassName, strMethodName, vector<ADWMIParam>());
}
IWbemClassObject* ADWMISearch::callStaticMethod(IWbemServices *pSvc, IWbemClassObject *pClass, CString strClassName,
CString strMethodName, vector<ADWMIParam> &arguments)
{
_bstr_t bstrClassName = _bstr_t(strClassName);
_bstr_t bstrMethodName = _bstr_t(strMethodName);
BOOL bInParams;
BOOL bOutParams;
HRESULT hResult;
IWbemClassObject* pClass2 = getWMIClass(pSvc, strClassName);
IWbemClassObject* pInParamsDefinition = NULL;
IWbemClassObject* pOutParamsDefinition = NULL;
hResult = pClass2->GetMethod(bstrMethodName, 0, &pInParamsDefinition, &pOutParamsDefinition);
if (hResult != WBEM_S_NO_ERROR)
{
//pClass->Release();
MyMessageBox_Error(_T("callStaticMethod"));
return NULL;
}
if (pInParamsDefinition == NULL)
{
bInParams = FALSE;
}
else
{
bInParams = TRUE;
}
if (pOutParamsDefinition == NULL)
{
bOutParams = FALSE;
}
else
{
bOutParams = TRUE;
}
IWbemClassObject* pInParamsInstance = NULL;
if (bInParams)
{
hResult = pInParamsDefinition->SpawnInstance(0, &pInParamsInstance);
for (int i = 0; i < arguments.size(); i ++)
{
_variant_t varArg;
VariantCopy(&varArg, &(arguments[i].value));
hResult = pInParamsInstance->Put(_bstr_t(arguments[i].key), 0, &varArg, 0);
//hResult = pInParamsInstance->Put(_bstr_t(arguments[i].key), 0, &(arguments[i].value), 0);
}
}
IWbemClassObject* pOutParams = NULL;
hResult = pSvc->ExecMethod(bstrClassName, bstrMethodName, 0, NULL, pInParamsInstance, &pOutParams, NULL);
if (hResult != WBEM_S_NO_ERROR)
{
//pClass->Release();
if (pInParamsDefinition != NULL)
{
pInParamsDefinition->Release();
}
if (pOutParamsDefinition != NULL)
{
pOutParamsDefinition->Release();
}
if (pInParamsInstance != NULL)
{
pInParamsInstance->Release();
}
MyMessageBox_Error(_T("callStaticMethod"));
return NULL;
}
if (pInParamsDefinition != NULL)
{
pInParamsDefinition->Release();
}
if (pOutParamsDefinition != NULL)
{
pOutParamsDefinition->Release();
}
if (pInParamsInstance != NULL)
{
pInParamsInstance->Release();
}
if (bOutParams)
{
return pOutParams;
}
else
{
return NULL;
}
}
IWbemClassObject* ADWMISearch::callMethod(IWbemServices *pSvc, IWbemClassObject *pClass, CString strClassName,
CString strInstancePath, CString strMethodName)
{
return callMethod(pSvc, pClass, strClassName, strInstancePath, strMethodName, vector<ADWMIParam>());
}
IWbemClassObject* ADWMISearch::callMethod(IWbemServices *pSvc, IWbemClassObject *pClass, CString strClassName,
CString strInstancePath, CString strMethodName, vector<ADWMIParam> &arguments)
{
_bstr_t bstrClassName = _bstr_t(strClassName);
_bstr_t bstrMethodName = _bstr_t(strMethodName);
BOOL bInParams;
BOOL bOutParams;
HRESULT hResult;
//IWbemClassObject* pClass = getWMIClass(pSvc, strClassName);
IWbemClassObject* pInParamsDefinition = NULL;
IWbemClassObject* pOutParamsDefinition = NULL;
hResult = pClass->GetMethod(bstrMethodName, 0, &pInParamsDefinition, &pOutParamsDefinition);
if (hResult != WBEM_S_NO_ERROR)
{
//pClass->Release();
MyMessageBox_Error(_T("callMethod"));
return NULL;
}
if (pInParamsDefinition == NULL)
{
bInParams = FALSE;
}
else
{
bInParams = TRUE;
}
if (pOutParamsDefinition == NULL)
{
bOutParams = FALSE;
}
else
{
bOutParams = TRUE;
}
IWbemClassObject* pInParamsInstance = NULL;
if (bInParams)
{
hResult = pInParamsDefinition->SpawnInstance(0, &pInParamsInstance);
for (int i = 0; i < arguments.size(); i ++)
{
_variant_t varArg;
VariantCopy(&varArg, &(arguments[i].value));
hResult = pInParamsInstance->Put(_bstr_t(arguments[i].key), 0, &varArg, 0);
//hResult = pInParamsInstance->Put(_bstr_t(arguments[i].key), 0, &(arguments[i].value), 0);
}
}
IWbemClassObject* pOutParams = NULL;
hResult = pSvc->ExecMethod(_bstr_t(strInstancePath), bstrMethodName, 0, NULL, pInParamsInstance, &pOutParams, NULL);
if (hResult != WBEM_S_NO_ERROR)
{
//pClass->Release();
if (pInParamsDefinition != NULL)
{
pInParamsDefinition->Release();
}
if (pOutParamsDefinition != NULL)
{
pOutParamsDefinition->Release();
}
if (pInParamsInstance != NULL)
{
pInParamsInstance->Release();
}
MyMessageBox_Error(_T("callMethod"));
return NULL;
}
if (pInParamsDefinition != NULL)
{
pInParamsDefinition->Release();
}
if (pOutParamsDefinition != NULL)
{
pOutParamsDefinition->Release();
}
if (pInParamsInstance != NULL)
{
pInParamsInstance->Release();
}
if (bOutParams)
{
return pOutParams;
}
else
{
return NULL;
}
}
void ADWMISearch::disconnect(IWbemServices *pSvc)
{
pSvc->Release();
CoUninitialize();
}
ADWMISearch.h
#include <Wbemidl.h>
#include <vector>
#include <map>
using namespace std;
class ADWMIParam
{
public:
CString key;
_variant_t value;
public:
ADWMIParam(CString strKey, CString strValue)
{
key = strKey;
VariantInit(&value);
value.vt = VT_BSTR;
value.bstrVal = _bstr_t(strValue);
}
ADWMIParam(CString strKey, IWbemClassObject *pValue)
{
key = strKey;
VariantInit(&value);
value.vt = VT_UNKNOWN;
value.punkVal = pValue;
}
};
class ADWMISearch
{
public:
DWORD WIN32_FROM_HRESULT_alternate(HRESULT hr);
IWbemServices* connect(CString strServerName, CString strServerIP, CString strDomainName,
CString strUsername, CString strPassword);
vector<IWbemClassObject*> query(IWbemServices *pSvc, CString strDomainName, CString strPassword, CString strWQL);
CString getStringFromObject(IWbemClassObject* pObject, CString strPropertyName);
vector<CString> getStringsFromObjects(vector<IWbemClassObject*> npObjects, CString strPropertyName);
void clearObjects(vector<IWbemClassObject*> npObjects);
IWbemClassObject* getWMIClass(IWbemServices *pSvc, CString strClassName);
IWbemClassObject* getObjectFromObject(IWbemClassObject *pObject, CString strArgumentName);
IWbemClassObject* getObjectFromObjectWithCheck(IWbemClassObject *pOutParams, CString strArgumentName);
vector<ADWMIParam> genObjectArguments(CString strArgName, IWbemClassObject *pObject);
IWbemClassObject* callStaticMethod(IWbemServices *pSvc, IWbemClassObject *pClass, CString strClassName,
CString strMethodName);
IWbemClassObject* callStaticMethod(IWbemServices *pSvc, IWbemClassObject *pClass, CString strClassName,
CString strMethodName, vector<ADWMIParam> &arguments);
IWbemClassObject* callMethod(IWbemServices *pSvc, IWbemClassObject *pClass, CString strClassName,
CString strInstancePath, CString strMethodName);
IWbemClassObject* callMethod(IWbemServices *pSvc, IWbemClassObject *pClass, CString strClassName,
CString strInstancePath, CString strMethodName, vector<ADWMIParam> &arguments);
void disconnect(IWbemServices *pSvc);
};
the call code(a place like main is ok)
ADWMISearch *wmiSearcher = new ADWMISearch();
IWbemServices *pSvc = wmiSearcher->connect("luo-pc", "127.0.0.1", "", "", "");
IWbemClassObject *pLSSSClass = wmiSearcher->getWMIClass(pSvc, "Win32_LogicalShareSecuritySetting");
vector<IWbemClassObject*> npObjects = wmiSearcher->query(pSvc, "", "", "Select * from Win32_Log