0

I want check if my application is already running and close the duplicate instance.

Into my code use a semaphore based on the application file name, if already exists, halt the new instance:

program MyProgram;

uses
  Vcl.Forms,
  Winapi.Windows,
  Vcl.Dialogs,
  System.SysUtils,
  System.UITypes,
  WinMain in 'WinMain.pas' {WMain};

{$R *.res}

var
  aSemafor: THandle;
  aAppName: string;
begin
  aAppName := ExtractFilename(Application.ExeName);
  aSemafor := CreateSemaphore(nil, 0, 1, PWideChar(aAppName));
  if (aSemafor <> 0) and (GetLastError = ERROR_ALREADY_EXISTS) then
  begin
    CloseHandle(aSemafor);
    MessageDlg(Format('Application "%s" is already running!', [aAppName]), mtError, [mbOk], 0);
    Halt;
  end;

  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TWMain, WMain);
  Application.Run;
end.

t works...

The question is: there is a standard/common way for make that?

i see some users use a mutex but it seem the same approch of semaphore, others iterate over the process list and check if already exists the same process name...

ar099968
  • 6,963
  • 12
  • 64
  • 127

0 Answers0