[fpc-pascal] single application instance
Alexey Pavluchenko
pavluchenko at isp.kiev.ua
Fri Sep 23 10:34:44 CEST 2005
Hello Jose,
Thursday, September 22, 2005, 1:20:48 PM, you wrote:
JP> How can avoid to run my program more than once?
I suppose you wanted to ask "how can I allow only one instance of my
program running under Win32". Correct me if I'm wrong. If I'm right,
then you may do it like this: check for named mutex with the name
unique to your program, if it does not exist then create it, if it
does then terminate the program. The following code is from APPINIT
unit written by Marc Batchelor:
=== cut ===
procedure InitInstance;
begin
{ Check to see if the mutex is already there }
InstanceMutexHandle := OpenMutex(MUTEX_ALL_ACCESS, false,
@UniqueApplicationString[1]);
if InstanceMutexHandle = 0 then
begin
{ This is the first instance }
InstanceMutexHandle := CreateMutex(nil, false,
@UniqueApplicationString[1]);
{ Error checking to see if anyone beat us... }
if InstanceMutexHandle = 0 then
IsFirstInstance := false
else
IsFirstInstance := true;
end
else
IsFirstInstance := false;
end;
=== cut ===
UniqueApplicationString in the above example is a shortstring, if you
use ansistring then you don't need '@' operator and '[1]' index, just
typecast it to pchar. The string should be unique system-wide so it is
probably best to generate it based on some pseudo-random numbers.
--
Best regards,
Alexey
More information about the fpc-pascal
mailing list