Thursday, November 15, 2007

Create a shortcut programatically.

Have you ever tried to create a shortcut programmatically? Here’s a way to achieve it:

CoInitialize( NULL );

IShellLink* psl;

CString PathLink = "C:\\Link.lnk";

// Get a pointer to the IShellLink interface.

HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,

IID_IShellLink, (PVOID *) &psl);

if (SUCCEEDED(hres))

{

IPersistFile* ppf;

// Set the path to the shortcut target and add the

// description.

psl->SetPath((LPCSTR) "D:\\My Folder\\MyFile.txt");

psl->SetWorkingDirectory((LPCSTR) " D:\\My Folder ");

psl->SetDescription((LPCSTR) "Programmatic shortcut!!!" );

hres = psl->QueryInterface(IID_IPersistFile, (PVOID *) &ppf);

if (SUCCEEDED(hres))

{

WORD wsz[MAX_PATH];

MultiByteToWideChar(CP_ACP, 0, (LPCSTR) PathLink, -1, wsz, MAX_PATH);

hres = ppf->Save(wsz, TRUE);

ppf->Release();

}

psl->Release();

}

CoUninitialize();

Using this method you can create shortcuts for any file or folder.

No comments: