2004. december 19., vasárnap

Create a standard windows shortcut file


Problem/Question/Abstract:

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();

program kg_MakeLink;

{****************************************************************}
{*                                                              *}
{* Language:    Delphi 3.00, 32 bit                             *}
{*              All code is within this one source file.        *}
{*                                                              *}
{* Description: Used to programmically create a 'ShortCut' to a *}
{*              DOS batch file. The ShortCut when invoked will  *}
{*              run in a minimized state. Location of newly     *}
{*              created ShortCut is in the same directory as    *}
{*              the batch file.                                 *}
{*                                                              *}
{* Comments:    It is up to the programmer to insure that all   *}
{*              commands called in the batch file are valid.    *}
{*                                                              *}
{* Suggestions: Attempt running the batch file under abnormal   *}
{*              conditions to see how things go, does the DOS   *}
{*              calls hang? etc.                                *}
{*                                                              *}
{* Error Codes: 0 = Success                                     *}
{*              1 = Either to many or not enough parameters     *}
{*              2 = File passed to this util, does not exist    *}
{*              3 = Failed to created ShortCut                  *}
{****************************************************************}
uses
  Windows, ShlObj, ActiveX, ComObj, SysUtils, Dialogs;

{$R *.RES}

procedure CreateLink(Target, Args, WorkDir, ShortCutName: string);
var
  IObj: IUnknown;
  Link: IShellLink;
  IPFile: IPersistFile;
  TargetW: WideString;
begin
  IObj := CreateComObject(CLSID_ShellLink);
  Link := IObj as IShellLink;
  IPFile := IObj as IPersistFile;

  with Link do
  begin
    SetPath(PChar(Target));
    SetArguments(PChar(Args));
    SetShowCmd(SW_SHOWMINIMIZED);
    SetWorkingDirectory(PChar(WorkDir));
  end;
  TargetW := ShortCutName;
  IPFile.Save(PWChar(TargetW), False);
end;

var
  a, b: string;

begin
  if ParamCount = 1 then
  begin
    a := ParamStr(1);
    if FileExists(a) then
    begin
      ShowMessage('A = ' + a);
      b := ExtractFilename(a) + '.lnk';
      ShowMessage('B = ' + b);
      try
        CreateLink(a, '', '', ExtractFileDir(a) + #92 + b);
      except
        halt(3); { Failed to create shortcut }
      end;
    end
    else
      halt(2); { File does not exist }
  end
  else
    halt(1); { Wrong amount of arguments }
end.

Nincsenek megjegyzések:

Megjegyzés küldése