Mega Code Archive

 
Categories / Delphi / Examples
 

How to create shortcuts

There is no single API call to create a shortcut. You rather have to use IShellLink OLE interface for this purpose. See the following sample code: uses Windows, Ole2, ShlObj, SysUtils, Forms; procedure CreateLink(ObjectPath: string; // path of the file/folder to create a shortcut LinkPath: string; // path of the newly created link/shortcut Description : string); var ShellLink : IShellLink; var PersistFile : IPersistFile; var WidePath : array[0..259] of WideChar; begin // initialize COM library CoInitialize; // Get a pointer to the IShellLink interface. if Failed(CoCreateInstance(CLSID_ShellLink,nil,CLSCTX_INPROC_SERVER, IID_IShellLink,ShellLink)) then raise Exception.Create('Unable to create an IShellLink instance'); try // set the path to the shortcut target ShellLink.SetPath(PChar(ObjectPath)); // set the Link description ShellLink.SetDescription(PChar(Description)); // Query IShellLink for the IPersistFile interface for saving the // shortcut in persistent storage. if Failed(ShellLink.QueryInterface(IID_IPersistFile,PersistFile)) then raise Exception.Create('Unable to create an IPersistFile instance'); try // ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, PChar(LinkPath), -1,WidePath, 259); // save the link by calling IPersistFile::Save. if Failed(PersistFile.Save(WidePath, TRUE)) then raise Exception.Create('Unable to save link'); finally // free the IPersistFile interface PersistFile.Release; end; // unitialize COM library CoUninitialize; finally // free the IShellLink interface ShellLink.Release; end; end; If you want to create your shortcut in a "special" directory, check the WinAPI helpfile for a description of the ShGetSpecialFolderLocation() function.