COM编程学习笔记

平时分析病毒时,难免遇到一些用COM的,分析这种时比较头疼。找到一篇老外写的文章,通俗易懂,跟着练习了一把,消除对COM的陌生感!

文章地址 :

  • https://www.codeproject.com/Articles/633/Introduction-to-COM-What-It-Is-and-How-to-Use-It
  • https://www.codeproject.com/Articles/901/Introduction-to-COM-Part-II-Behind-the-Scenes-of-a
  • https://www.codeproject.com/Articles/13601/COM-in-plain-C

而且这个老外还发布过一些IE扩展的文章,感觉也不错:
https://www.codeproject.com/Articles/Michael-Dunn#Article

下面是根据第一篇文章写的COM Client的代码。

学习目的:COM客户端,多接口和单接口的查询使用。

实现功能:使用单接口查询当前电脑壁纸图片路径,然后通过多接口来实现生成一个lnk快捷方式

#include "stdafx.h"
#include 
#include "Wininet.h "
#include "winnls.h"
#include 
#include "shobjidl.h"
#include 
#include "objidl.h"
#include "shlguid.h"
#include 

using namespace std;

WCHAR* GetWallpaperPath()
{
	WCHAR wszWallpaper[MAX_PATH];
	HRESULT hr;
	IActiveDesktop* pIAD;


	CoInitialize(NULL);

	hr = CoCreateInstance(CLSID_ActiveDesktop, NULL, CLSCTX_INPROC_SERVER, IID_IActiveDesktop, (void**)&pIAD);
	if (SUCCEEDED(hr))
	{
		// Call methods using pISL here.
		hr = pIAD->GetWallpaper(wszWallpaper, MAX_PATH, 0);
		if (SUCCEEDED(hr))
		{
			wcout << L"Wallpaper path is: \n   " << wszWallpaper << endl << endl;
		}
		else
		{
			cout << _T("GetWallpaper() failed.") << endl << endl;
		}

		// Tell the COM object that we're done with it.
		pIAD->Release();
	}
	else
	{
		// Couldn't create the COM Object. hr holds the error code.
		printf("Couldn't create the COM Object. err code: %d", &hr);
	}
	CoUninitialize();

	return wszWallpaper;

}

void demo2()
{
	HRESULT hr;
	IShellLink* pISL;
	IPersistFile* pIPF;


	CoInitialize(NULL);

	hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&pISL);
	if (SUCCEEDED(hr))
	{
		// Call methods using pISL here.
		hr = pISL->SetPath(GetWallpaperPath());
		if (SUCCEEDED(hr))
		{
			// Get the second interface from the COM Object.
			hr = pISL->QueryInterface(IID_IPersistFile, (void**)&pIPF);
			if (SUCCEEDED(hr))
			{
				hr = pIPF->Save(L"d:\\wallpaper.lnk", FALSE);
				pIPF->Release();
			}
		}

		// Tell the COM object that we're done with it.
		pISL->Release();
	}
	else
	{
		// Couldn't create the COM Object. hr holds the error code.
		printf("Couldn't create the COM Object. err code: %d", &hr);
	}
	CoUninitialize();
}


int _tmain(int argc, _TCHAR* argv[])
{
	demo2();

	return 0;
}

你可能感兴趣的:(COM)