Delphi – Create a single instance of your app

Hi guys. After searching for a while on how to lock and limit the app clicking. And this is now possible.

Here is the code for the main project file

program Project2;

 

uses

Forms, Windows, Messages, Dialogs,

Unit1 in ‘Unit1.pas’ {Form1};

 

{$R *.res}

 

function CreateSingleInstance(const InstanceName: string): boolean;

var

MutexHandle: THandle;

begin

MutexHandle := CreateMutex(nil, false, PChar(InstanceName));

// if MutexHandle created check if already exists

if (MutexHandle <> 0) then

begin

if GetLastError = ERROR_ALREADY_EXISTS then

begin

Result := false;

CloseHandle(MutexHandle);

end

else Result := true;

end

else Result := false;

end;

 

var

MyInstanceName: string;

begin

MyInstanceName := ‘Project2’;

Application.Initialize;

// Initialize MyInstanceName here

if CreateSingleInstance(MyInstanceName) then

begin

// Form creation

Application.CreateForm(TForm1, Form1);

Application.Run;

end

else Application.Terminate;

end.