The component Uniqueinstance can do this job for you, to use it just drop a component in the main form, manipulate the property Identifier
(used to identify your application) and activate it.
You can also do this using the function CreateMutex()
for identify the application, if the function succeeds the return value will be identity otherwise a null value.
If such an identifier already exists before calling the function, the return will be the identifier for the existing object, in which case when calling the function GetLastError()
, the return value will be ERROR_ALREADY_EXISTS
. That in practice would be 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 event OnCreate()
of the main form. To release the identifier you can use the function CloseHandle()
at the event OnClose()
or OnDestroy()
, for this the variable mutex
would have to be a global variable.
Thank you, you helped me a lot.
– Corvo