[対象バージョン]
Delphi 3.0J
[説明]
Delphiでアプリケーションの二重起動を防止する方法です。
[対処法]
いろいろな方法があるようですが、「Delphi 3 テクニカルハンドブック」にも掲載されていてボーランド推奨(?)の「アトム」を使って対処します。Windows API の GlobalAddAtom GlobalFindAtom を利用します。 メニューの「表示」ー「プロジェクトソース」を選択して、以下のようなコードを加えます。
[サンプルソース]
program Project1; uses Windows, SysUtils, Dialogs, 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 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.