The UniqueInstance component can do this work for you, just use it a component in the main form, manipulates the Identifier
property (used to identify your application) and activates it.
You can also do this by using the CreateMutex()
> to identify the application, if the function succeeds the return value will be the identity of the application, otherwise a null value.
If this identifier already exists before calling the function, the return will be the identifier for the existing object, in this case, when calling the function GetLastError()
, the return value will be ERROR_ALREADY_EXISTS
. This in practice would look something like this:
var
mutex: THandle;
ID: string;
begin
ID:= 'MyAppUniqueID';
mutex := CreateMutex(nil, False, PChar(ID));
if GetLastError = ERROR_ALREADY_EXISTS then begin
Application.Terminate;
end;
end;
The code snippet above can be used in the OnCreate()
event of the main form. To release the identifier you can use the CloseHandle()
> in the event OnClose()
or OnDestroy()
, for this the variable mutex
would have to be a global variable.