二重起動防止

プログラムのProjectファイルに下記のように記述すると、
既に起動済みならプログラムを最前面に出し起動していなければ
通常通り起動します。

使用コンポーネント
なし


uses
 Windows, SysUtils, Dialogs, Messages, Forms,
 Unit1 in 'Unit1.pas' {Form1};

{$R *.RES}

var
 Atm: TAtom; {アトム値}
 hApp: THandle; {アプリケーションのハンドル}
begin
 {GlobalFindAtomでアプリケーション名が登録済みか調べる}
 Atm := GlobalFindAtom(PChar(ExtractFileName(Application.ExeName)));

 {戻り値が0以外ならすでに登録されている=起動されている}
 {既に起動されている場合・・前面に表示するのみ}
 {起動されていない場合 ・・アトム値を登録する}
 if Atm <> 0 then
 begin
  {自分と同じタイトルのアプリケーションを探す}
  hApp := FindWindow(nil, 'Sample Application');
  if hApp <> 0 then
  begin
   SendMessage(hApp, WM_SYSCOMMAND, SC_RESTORE, 0);
   SetForeGroundWindow(hApp);
   exit;
  end;
 end
 else
 begin
  {GlobalAddAtomで新規のアトム値を登録する}
  Atm := GlobalAddAtom(PChar(ExtractFileNAme(Application.ExeName)));
  {Atm が0ならアトム値が登録できなかったのでエラーにする}
  if Atm = 0 then
  begin
   ShowMessage('起動できません');
   exit;
  end;
 end;

 Application.Initialize;

 {アプリケーションのタイトルを登録する}
 Application.Title := 'Sample Application';

 Application.CreateForm(TForm1, Form1);
 Application.Run;

 {アプリケーションが終了したらアトム値を削除する}
 GlobalDeleteAtom(Atm);

end.