Prevent Multiple Instance of the Application

Hi all
I inserted the following call to the dpr file of the application to prevent the multiple instances. But did not succeeded.

function isOneInstance(): Boolean;
Var
  Handle: THandle;
  ErrCode: DWORD;
Begin
  Result:= False;
  Handle:= 0;

  try
    Handle:= CreateMutex(nil, False, 'Global\_AFB2FB05-5FA5-4C9E-9633-2353418AFF7E');
    if(Handle= 0) then exit();
    if GetLastError() = ERROR_ALREADY_EXISTS then exit();

    Result:= True;
  finally
    if(Handle<>0) then begin
      ReleaseMutex(Handle);
      CloseHandle(Handle);
    end;
    Handle:= 0;
  end;
End;


begin
  if(isOneInstance()) then begin
    Application.Initialize;
    Application.MainFormOnTaskbar := True;
    Application.CreateForm(TForm1, Form1);
    Application.Run;
  end else begin
    Application.MessageBox('Already Running', 'WARNING', MB_OK);
    Application.Terminate();
  end;
end.

What is wrong with that code did not understand. I inserted Global\ to the mutex string to have that mutex object in the global name spaces also but did not work anyway

Best Regards,

Even using True to request the intial ownership did not make any difference.

The Mutex needs to exist for the life of the program. You are closing the Mutex at the end of the isOneInstance function.

1 Like

Thank you for your fast response.
After your reply, I shocked that how I did that mistake.

Regards,