picture

Create a Desktop Icon in Delphi.

Sometimes you need to place an icon on the desktop, pointing to a particular directory/file. The code below demonstrates how to do it.


procedure CreateDesktopIcon(folderPath : string;
                            iconName : WideString) ;
var
   IObject : IUnknown;
   ISLink : IShellLink;
   IPFile : IPersistFile;
   PIDL : PItemIDList;
   InFolder : array[0..MAX_PATH] of Char;
   TargetName : String;
   LinkName : WideString;
begin
   TargetName := folderPath;
   try
     IObject := CreateComObject(CLSID_ShellLink) ;
     ISLink := IObject as IShellLink;
     IPFile := IObject as IPersistFile;

     with ISLink do
     begin
       SetPath(pChar(TargetName)) ;
       SetWorkingDirectory(pChar(ExtractFilePath(TargetName))) ;
     end;

     // if we want to place a link on the Desktop
     SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, PIDL) ;
     SHGetPathFromIDList(PIDL, InFolder) ;    

     iconName :=  '\' + iconName + '.lnk';
     LinkName := InFolder + iconName;
     IPFile.Save(PWChar(LinkName), false) ;
     except
       ShowMessage('Error!');
     end;
end;

Leave a Reply

For spam detection purposes, please copy the number 4175 to the field below: