interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
ShlObj, ActiveX, ComObj; {該函數使用的單元}
{函數說明:}
{第一個參數是要建立快捷方式的文件, 這是必須的; 其他都是可選參數}
{第二個參數是快捷方式名稱, 缺省使用參數一的文件名}
{第三個參數是指定目的文件夾, 缺省目的是桌面; 如果有第四個參數, 該參數將被忽略}
{第四個參數是用常數的方式指定目的文件夾; 該系列常數定義在 ShlObj 單元, CSIDL_ 打頭}
function CreateShortcut(Exe:string; Lnk:string = ''; Dir:string = ''; ID:Integer = -1):Boolean;
var
IObj: IUnknown;
ILnk: IShellLink;
IPFile: IPersistFile;
PIDL: PItemIDList;
InFolder: array[0..MAX_PATH] of Char;
LinkFileName: WideString;
begin
Result := False;
if not FileExists(Exe) then Exit;
if Lnk = '' then Lnk := ChangeFileExt(ExtractFileName(Exe), '');
IObj := CreateComObject(CLSID_ShellLink);
ILnk := IObj as IShellLink; ILnk.SetPath(PChar(Exe)); ILnk.SetWorkingDirectory(PChar(ExtractFilePath(Exe))); if (Dir = '') and (ID = -1) then ID := CSIDL_DESKTOP;
if ID > -1 then
begin
SHGetSpecialFolderLocation(0, ID, PIDL);
SHGetPathFromIDList(PIDL, InFolder);
LinkFileName := Format('%s%s.lnk', [InFolder, Lnk]);
end else
begin
Dir := ExcludeTrailingPathDelimiter(Dir);
if not DirectoryExists(Dir) then Exit;
LinkFileName := Format('%s%s.lnk', [Dir, Lnk]);
end;
IPFile := IObj as IPersistFile;
if IPFile.Save(PWideChar(LinkFileName), False) = 0 then Result := True;
end; {CreateShortcut 函數結束}
{測試 1: 把當前程序在桌面上建立快捷方式}
procedure TForm1.Button1Click(Sender: TObject);
begin
CreateShortcut(Application.ExeName);
end;
{測試 2: 在桌面上建立快捷方式, 同時指定快捷方式名稱}
procedure TForm1.Button2Click(Sender: TObject);
begin
CreateShortcut(Application.ExeName, 'NewLinkName');
end;
{測試 3: 在 C: 下建立快捷方式}
procedure TForm1.Button3Click(Sender: TObject);
begin
CreateShortcut(Application.ExeName, '', 'C:');
end;
{測試 3: 在開始菜單的程序文件夾下建立快捷方式}
procedure TForm1.Button4Click(Sender: TObject);
begin
CreateShortcut(Application.ExeName, '', '', CSIDL_PROGRAMS);
end;