In this article, you will learn how to create standard Windows shortcuts using Delphi code.
Creating a Shell Link - Shortcut
Add a button (button1) on a form (form1) and try this code:
uses ShlObj, ActiveX, ComObj;
...
procedure TForm1.Button1Click(Sender: TObject) ;
var
IObject : IUnknown;
ISLink : IShellLink;
IPFile : IPersistFile;
PIDL : PItemIDList;
InFolder : array[0..MAX_PATH] of Char;
TargetName : String;
LinkName : WideString;
begin
TargetName := 'c:\windows\calc.exe';
{Use TargetName:=ParamStr(0) which
returns the path and file name of the
executing program to create a link to your
Application}
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) ;
{
or if we want a link to appear in
some other, not-so-special, folder:
InFolder := 'c:\SomeFolder'
}
LinkName := InFolder + '\Delphi Created Link.lnk';
IPFile.Save(PWChar(LinkName), false) ;
end;
At the beginning of this code is the most important part.
The IShellLink designates an interface that allows an application to create shell links (.lnk files) or to access the information of an existing one. The IPersistFile interface provides methods for an object to load and save itself in a disk file. At this point, we can use several methods available to those interfaces:
. IShellLink.SetPath() sets the path and filename of a shell link object. The only parameter is a pChar to our TargetName.
. IShellLink.SetWorkingDirectory() sets the name of the working directory for a shell link object. We are getting the working directory by using Delphi's ExtractFilePath() function.
. IPersistFile.Save() saves a copy of the object into the specified file, which in our case creates the physical .LNK file.
In this example, a link to calc.exe (Windows calculator) is created on the Desktop. To get our Desktop directory folder we have to use SHGetSpecialFolderLocation API call. The second parameter in this call is the most important one: the integer value of the constant representing the SpecialFolder. For other constants (other special folders) take a look at Win32 help files.