使用C++进行WMI查询的简单封装

本文介绍如何使用C++创建一个简单的CWMIUtil类,用于封装WMI查询。类中提供的GetProperty函数针对VT_BSTR类型的属性进行了处理。示例展示了如何利用这个封装来获取进程路径,输入进程PID,输出进程的完整路径。
摘要由CSDN通过智能技术生成

封装WMI查询的简单类CWMIUtil


头文件WMIUtil.h

#pragma once
#include <Wbemidl.h>

class CWMIUtil
{
public:
	CWMIUtil(void);
	virtual ~CWMIUtil(void);

private:
	// 禁止复制和赋值
	CWMIUtil(const CWMIUtil&);
	CWMIUtil& operator = (const CWMIUtil&);

public:
	DWORD GetErrorCode() const;
	const TCHAR *GetErrorInfo() const;
private:
	void SetErrorCode(const DWORD dwErrorCode);
	void SetErrorInfo(const TCHAR *szFormat, ...);

public:
	BOOL Init();
	BOOL ConnectServer(const TCHAR *szServer = TEXT("ROOT\\CIMV2"));
	BOOL ExecQuery(const TCHAR *szQuerySql);
	BOOL Next();
	BOOL GetProperty(const TCHAR *szValueName, TCHAR *szValue, const DWORD dwSizeInByte);

private:
	DWORD m_dwErrorCode;
	CString m_csErrorInfo;

private:
	BOOL m_bInitComSuccess;

private:
	IWbemLocator *m_pLoc;
	IWbemServices *m_pSvc;
	IEnumWbemClassObject* m_pEnumerator;
	IWbemClassObject *m_pCurObj;
};


源文件WMIUtil.cpp

#include "stdafx.h"
#include "WMIUtil.h"

#define _WIN32_DCOM
#include <comdef.h>
# pragma comment(lib, "wbemuuid.lib")

CWMIUtil::CWMIUtil(void)
	: m_dwErrorCode(0), m_csErrorInfo(TEXT("")), m_bInitComSuccess(FALSE)
	, m_pLoc(NULL), m_pSvc(NULL), m_pEnumerator(NULL), m_pCurObj(NULL)
{
}

CWMIUtil::~CWMIUtil(void)
{
	try
	{
		// 释放对象
		if (m_pCurObj)
		{
			m_pCurObj->Release();
		}
		if (m_pEnumerator)
		{
			m_pEnumerator->Release();
		}
		if (m_pSvc)
		{
			m_pSvc->Release();
		}
		if (m_pLoc)
		{
			m_pLoc->Release();
		}
		if (m_bInitComSuccess)
		{
			CoUninitialize();
		}
	}
	catch (_com_error &e)
	{
		// COM exception
	}
	catch (CException &e)
	{
		// MFC exception
	}
	catch (...)
	{
		// all exception
	}
}

DWORD CWMIUtil::GetErrorCode() const
{
	return m_dwErrorCode;
}

const TCHAR *CWMIUtil::GetErrorInfo() const
{
	return m_csErrorInfo.GetStrin
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值