Create Links of File/Folder in VC++ using MFC

Make sure you call CoInitialize(NULL); before calling this function.

// CreateLink – uses the Shell’s IShellLink and IPersistFile interfaces
//   to create and store a shortcut to the specified object.
// Returns the result of calling the member functions of the interfaces.
// lpszPathObj – address of a buffer containing the path of the object.
// lpszPathLink – address of a buffer containing the path where the
//   Shell link is to be stored.
// lpszDesc – address of a buffer containing the description of the
//   Shell link.
HRESULT CreateLink(CString csPathObj, CString csPathLink, CString csDesc)
{
  HRESULT hres;
  IShellLink* psl;
  // Get a pointer to the IShellLink interface.
  hres = CoCreateInstance(CLSID_ShellLink, NULL,
  CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *) &psl);
  if (SUCCEEDED(hres))
  {
    IPersistFile* ppf;
    // Set the path to the shortcut target and add the description.
    psl->SetPath(csPathObj);
    psl->SetDescription(csDesc);
    // Query IShellLink for the IPersistFile interface for saving the
    // shortcut in persistent storage.
    hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);
    if (SUCCEEDED(hres))
    {
      WCHAR wsz[MAX_PATH];
      // Ensure that the string is Unicode.
      char * lpszLinkPath = new char[csPathLink.GetLength() + 1];
      wcstombs(lpszLinkPath, csPathLink, csPathLink.GetLength() + 1);
      MultiByteToWideChar(CP_ACP, 0, lpszLinkPath, -1, wsz, MAX_PATH);
      delete [] lpszLinkPath;
      // Save the link by calling IPersistFile::Save.
      hres = ppf->Save(wsz, TRUE);
      ppf->Release();
    }
    psl->Release();
  }
  return hres;
}

Thanks to Ali!
[link] http://groups.google.com.pk/group/comp.os.ms-windows.programmer.win32/browse_thread/thread/5bb2651a1536c2b8/65740934a19cf2eb?lnk=st&q=how+create+shortcut+using+vc&rnum=1&hl=en#65740934a19cf2eb

4 thoughts on “Create Links of File/Folder in VC++ using MFC

  1. I think loop is not hard job. You can make your program as you like but main thing is function to be use… which I have told you…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s