Creating a shortcut with ATL

by Codewiz51 May 02, 2009 18:03

Have you ever wondered how to create a shortcut programmatically? The web is buried with examples using VB or Javascript. Here's how you do it with C++ and ATL:

// CreateShortCut
// Params:
// file:        The file to link to
// startIn:     The Start In directory
// shortCut:    Where to write the link
// Return Value:
// true -    Shortcut created.
// false -  Failed to create short cut
bool CShortcutDlg::CreateShortCut(CString file, CString startIn, CString shortCut)
{  
    CComPtr<IShellLink>        pISL;
    CComQIPtr<IPersistFile>    pIPF;

    if(FAILED(pISL.CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER)))
        return false;

    if(FAILED(pISL->SetPath(file)))
        return false;

    if(FAILED(pISL->SetWorkingDirectory(startIn)))
        return false;

    // There are a large number of properties available in
    // IShellLink.
    //if(FAILED(pISL->SetIconLocation(pszIconPath, iconIndex))
    //    return false;

    if(SUCCEEDED(pISL->QueryInterface<IPersistFile>(&pIPF)))
        pIPF->Save(shortCut,FALSE);
    else  
        return false;

    return true;
}

It turns out you need access to two COM interfaces in order to create the interface: IShellLink and IPersistFile. Using ATL CComPtr templates decreases the amount of boiler plate code needed to implement this task. (You may also assign accelerators and icons through the pISL pointer.)

Comments are closed

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen | Modified by Mooglegiant

Disclaimer

This blog represents my personal hobby, observations and views. It does not represent the views of my employer, clients, especially my wife, children, in-laws, clergy, the dog, the cats or my daughter's horse. In fact, I am not even sure it represents my views when I take the time to reread postings.

© Copyright 2008-2011