Author: William Gerbert
How can I create a standard windows shortcut file (*.lnk) from my Delphi
application?
Answer:
Below is an example that creates a shortcut to a DOS batch file. You need to use
the procedure CreateLink();
1 program kg_MakeLink;
2
3 {****************************************************************}
4 {* *}
5 {* Language: Delphi 3.00, 32 bit *}
6 {* All code is within this one source file. *}
7 {* *}
8 {* Description: Used to programmically create a 'ShortCut' to a *}
9 {* DOS batch file. The ShortCut when invoked will *}
10 {* run in a minimized state. Location of newly *}
11 {* created ShortCut is in the same directory as *}
12 {* the batch file. *}
13 {* *}
14 {* Comments: It is up to the programmer to insure that all *}
15 {* commands called in the batch file are valid. *}
16 {* *}
17 {* Suggestions: Attempt running the batch file under abnormal *}
18 {* conditions to see how things go, does the DOS *}
19 {* calls hang? etc. *}
20 {* *}
21 {* Error Codes: 0 = Success *}
22 {* 1 = Either to many or not enough parameters *}
23 {* 2 = File passed to this util, does not exist *}
24 {* 3 = Failed to created ShortCut *}
25 {****************************************************************}
26 uses
27 Windows, ShlObj, ActiveX, ComObj, SysUtils, Dialogs;
28
29 {$R *.RES}
30
31 procedure CreateLink(Target, Args, WorkDir, ShortCutName: string);
32 var
33 IObj: IUnknown;
34 Link: IShellLink;
35 IPFile: IPersistFile;
36 TargetW: WideString;
37 begin
38 IObj := CreateComObject(CLSID_ShellLink);
39 Link := IObj as IShellLink;
40 IPFile := IObj as IPersistFile;
41
42 with Link do
43 begin
44 SetPath(PChar(Target));
45 SetArguments(PChar(Args));
46 SetShowCmd(SW_SHOWMINIMIZED);
47 SetWorkingDirectory(PChar(WorkDir));
48 end;
49 TargetW := ShortCutName;
50 IPFile.Save(PWChar(TargetW), False);
51 end;
52
53 var
54 a, b: string;
55
56 begin
57 if ParamCount = 1 then
58 begin
59 a := ParamStr(1);
60 if FileExists(a) then
61 begin
62 ShowMessage('A = ' + a);
63 b := ExtractFilename(a) + '.lnk';
64 ShowMessage('B = ' + b);
65 try
66 CreateLink(a, '', '', ExtractFileDir(a) + #92 + b);
67 except
68 halt(3); { Failed to create shortcut }
69 end;
70 end
71 else
72 halt(2); { File does not exist }
73 end
74 else
75 halt(1); { Wrong amount of arguments }
76 end.
|