03
Jul 08

Delphi: Utils :: AppSingleton

:: articles :: by Gilberto Saraiva

Folks,

This code below implement a singleton structure for the aplication, and that need to be implemented on the DPR file of the project:

 Delphi |  copy code |? 
01
uses Windows;
02
 
03
function AppSingleton(ACheckPath: boolean = false): boolean;
04
var
05
  s: string;
06
  i, iLast: Cardinal;
07
begin
08
  s := ParamStr(0);
09
  iLast := 1;
10
  case Integer(ACheckPath) of
11
    0: for i := 1 to Length(s) do if s[i] = '\' then iLast := i;
12
    1: for i := 1 to Length(s) do if s[i] in [':','\','.',' '] then s[i] := '_';
13
  end;
14
  Result := (CreateMutex(nil, true, PChar(Cardinal(@s) + (iLast - 1))) <> 0) and
15
    (GetLastError = 0);
16
end;

I use the CreateMutex API that works as a semaphore, if open, the application is unique, if closed the application is already running.

I wrote a condition to check the full path of the application for the Mutex call, so if you want to check the full path use the funciotn with param as True, the default is False and the check will be only on the application exe name.

A little detail about checking the functionality of this function:
Under debug mode the checkout on full path mode will fail and more then one application can be raised. This problem is because the relationship of the application with other program, so the CreateMutex API understand the Process ID is diferent from others.

Tags: , , ,


Leave a comment