让 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.

你可能感兴趣的:(程序,Delphi,一个副本)