讓 Delphi 程序只運行一個副本

program mutex;

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

{$R *.res}

const
  MutexStr = '4C3201D5-6A5A-4B8B-A2F0-B103985705F4'; // GUID

var
  hAppMutex: THandle;

begin
  ReportMemoryLeaksOnShutdown := DebugHook = 1;
  Application.Initialize;
  hAppMutex := CreateMutex(nil, False, PChar(MutexStr));
  if (hAppMutex = 0) then begin
   Application.MessageBox('建立互斥對象失敗!', '錯誤提示', MB_ICONSTOP);
   exit;
  end;
  if ((hAppMutex <> 0) and (GetLastError() = ERROR_ALREADY_EXISTS)) then begin
   Application.MessageBox('本程序只能運行一個副本!', '錯誤提示', MB_ICONSTOP);
   CloseHandle(hAppMutex);
   exit;
  end;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
  CloseHandle(hAppMutex);
end.orm

相關文章
相關標籤/搜索