Click here to Skip to main content
15,886,110 members
Articles / Desktop Programming / ATL

Introduction to COM - What It Is and How to Use It.

Rate me:
Please Sign up or sign in to vote.
4.91/5 (513 votes)
27 Jul 2000 2.2M   15.7K   978  
A tutorial for programmers new to COM that explains how to reuse existing COM components, for example, components in the Windows shell.
// COMIntro.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "COMIntro.h"
#include <atlconv.h>                    // ATL string conversion macros

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
        {
        cerr << _T("Fatal Error: MFC initialization failed") << endl;
        return 1;
        }

    // Init the COM library - have Windows load up the DLLs.
    if ( FAILED( CoInitialize(NULL) ))
        {
        cerr << _T("Fatal Error: OLE initialization failed") << endl;
        return 1;
        }

WCHAR   wszWallpaper [MAX_PATH];
HRESULT hr;
IActiveDesktop* pIAD;

    // Create a COM object from the Active Desktop coclass.
    hr = CoCreateInstance ( CLSID_ActiveDesktop,
                            NULL,
                            CLSCTX_INPROC_SERVER,
                            IID_IActiveDesktop,
                            (void**) &pIAD );

    if ( SUCCEEDED(hr) )
        {
        // Get the name of the wallpaper file.
        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;
            }

        // Release the IActiveDesktop interface, since we're done using it.
        pIAD->Release();
        }
    else
        {
        cout << _T("CoInitialize() failed.") << endl << endl;
        }

    // If anything above failed, quit the program.
    if ( FAILED(hr) )
        return 0;

CString       sWallpaper = wszWallpaper;    // Convert the Unicode string to ANSI.
IShellLink*   pISL;
IPersistFile* pIPF;

    // Create a COM object from the Shell Link coclass.
    hr = CoCreateInstance ( CLSID_ShellLink,
                            NULL,
                            CLSCTX_INPROC_SERVER,
                            IID_IShellLink,
                            (void**) &pISL );

    if ( SUCCEEDED(hr) )
        {
        // Set the path of the target file (the wallpaper).
        hr = pISL->SetPath ( sWallpaper );

        if ( SUCCEEDED(hr) )
            {
            // Get an IPersisteFile interface from the COM object.
            hr = pISL->QueryInterface ( IID_IPersistFile, (void**) &pIPF );

            if ( SUCCEEDED(hr) )
                {
                // Save the shortcut as "C:\wallpaper.lnk"  Note that the first
                // param to IPersistFile::Save() is a Unicode string, thus the L
                // prefix.
                hr = pIPF->Save ( L"C:\\wallpaper.lnk", FALSE );

                if ( SUCCEEDED(hr) )
                    {
                    cout << _T("Shortcut created.") << endl << endl;
                    }
                else
                    {
                    cout << _T("Save() failed.") << endl << endl;
                    }

                // Release the IPersistFile interface, since we're done with it.
                pIPF->Release();
                }
            else
                {
                cout << _T("QueryInterface() failed.") << endl << endl;
                }
            }
        else
            {
            cout << _T("SetPath() failed.") << endl << endl;
            }

        // Release the IShellLink interface too.
        pISL->Release();
        }
    else
        {
        cout << _T("CoCreateInstance() failed.") << endl << endl;
        }

    CoUninitialize();

    return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior) VMware
United States United States
Michael lives in sunny Mountain View, California. He started programming with an Apple //e in 4th grade, graduated from UCLA with a math degree in 1994, and immediately landed a job as a QA engineer at Symantec, working on the Norton AntiVirus team. He pretty much taught himself Windows and MFC programming, and in 1999 he designed and coded a new interface for Norton AntiVirus 2000.
Mike has been a a developer at Napster and at his own lil' startup, Zabersoft, a development company he co-founded with offices in Los Angeles and Odense, Denmark. Mike is now a senior engineer at VMware.

He also enjoys his hobbies of playing pinball, bike riding, photography, and Domion on Friday nights (current favorite combo: Village + double Pirate Ship). He would get his own snooker table too if they weren't so darn big! He is also sad that he's forgotten the languages he's studied: French, Mandarin Chinese, and Japanese.

Mike was a VC MVP from 2005 to 2009.

Comments and Discussions