2008年7月17日

ショートカットをプログラムから作成する

プログラムから実行ファイルへのショートカットを作成するにはCOMオブジェクトのシェルリンク機能をIShellLinkIPersistFileを使用して呼び出します。
uses
  SysUtils, ShlObj, ActiveX, ComObj;

function CreateShortCut(const Location: String;
                        const ShortcutName: String;
                        const FullPathname: String;
                        const Params: String;
                        const WorkingDir: String;
                        const Description: String): Boolean;
var
  Unknown: IUnknown;
  ShellLink: IShellLink;
  PersistFile: IPersistFile;
{$IFDEF Unicode}
  FileName: String;
{$ELSE}
  FileName: WideString;
{$ENDIF}
begin

  { Create shell link object }
  Unknown := CreateComObject(CLSID_ShellLink);

  { Get IShellLink/IPersistent inferface }
  ShellLink   := Unknown as IShellLink;
  PersistFile := Unknown as IPersistFile;

  { Set path to shell link }
  ShellLink.SetPath(PChar(FullPathname));

  { Set arguments to shell link }
  ShellLink.SetArguments(PChar(Params));

  { Set description string }
  ShellLink.SetDescription(PChar(Description));

  { Set working directory }
  ShellLink.SetWorkingDirectory(PChar(WorkingDir));

  { Set location (path and index) of the icon }
  ShellLink.SetIconLocation(PChar(FullPathname),0);

  { Save to file }
  FileName := IncludeTrailingPathDelimiter(Location) +
              ShortcutName + '.LNK';
{$IFDEF Unicode}
  Result := Succeeded(PersistFile.Save(PChar(FileName),True));
{$ELSE}
  Result := Succeeded(PersistFile.Save(PWChar(FileName),True));
{$ENDIF}

end;

元ねたは現Embarcadero Technologies社員でローカライズ担当の新井さんのDelphiの神託 DelphiによるCOMの徹底活用 シェルプログラミング入門(新井 正広著/ソフトバンク/ISBN4-7973-0782-X)。出版当時新井さんはまだ学生さんだった気がします。

2008/07/30追記: Windowsが管理している場所(スタートメニューなど)にショートカットを作成したときは
  SendMessage(HWND_BROADCAST,WM_SETTINGCHANGE,0,0);

を行わないと次回起動時まで表示に反映されない、という点に注意してください。

0 件のコメント: