Ver Mensaje Individual
  #1  
Antiguo 04-03-2007
Avatar de seoane
[seoane] seoane is offline
Miembro Premium
 
Registrado: feb 2004
Ubicación: A Coruña, España
Posts: 3.717
Reputación: 24
seoane Va por buen camino
Cuantas instancias de nuestro exe están corriendo

En un hilo surgió la pregunta de como averiguar cuantas instancias de nuestra aplicación están abiertas en un momento determinado.

La solución fue la siguiente:
Código Delphi [-]
uses PsApi;

function CuantosSomos: Integer;
var
  Procesos: array[1..1024] of DWORD;
  Needed, i: DWORD;
  Process: THandle;
  ModName: array[0..MAX_PATH] of Char;
begin
  Result:= 0;
  if EnumProcesses(@Procesos,SizeOf(Procesos),Needed) then
  begin
    for i:= 1 to (Needed div Sizeof(DWORD)) do
    begin
      Process := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ,
        FALSE,Procesos[i]);
      if Process <> 0 then
      begin
        if GetModuleFileNameEx(Process,0,ModName,SizeOf(ModName)-1)>0  then
        begin
          if StrIComp(ModName,PChar(ParamStr(0))) = 0 then
            inc(Result);
        end;
        CloseHandle(Process);
      end;
    end;
  end;
end;

// Por ejemplo
ShowMessage(IntToStr(CuantosSomos));

En ese mismo hilo surgió la duda de que pasaría si alguien copiase nuestra aplicación a otro lugar, le cambiase el nombre y la volviese a ejecutar. La solución que propuse fue la siguiente:
Código Delphi [-]
uses PsApi, Hashes;

function FSize(Path: String): Int64;
var
  SearchRec: TSearchRec;
begin
  if FindFirst(Path,faAnyFile,SearchRec) = 0 then
    Result:= SearchRec.Size
  else
    Result:= -1;
  FindClose(SearchRec);
end;

function CuantosSomos: Integer;
var
  Procesos: array[1..1024] of DWORD;
  Needed, i: DWORD;
  Process: THandle;
  ModName: array[0..MAX_PATH] of Char;
  Size: int64;
  Hash: String;
begin
  Result:= 0;
  Size:= FSize(ParamStr(0));
  Hash:= CheckSum(ParamStr(0));
  if EnumProcesses(@Procesos,SizeOf(Procesos),Needed) then
  begin
    for i:= 1 to (Needed div Sizeof(DWORD)) do
    begin
      Process := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ,
        FALSE,Procesos[i]);
      if Process <> 0 then
      begin
        if GetModuleFileNameEx(Process,0,ModName,SizeOf(ModName)-1)>0  then
        begin
          if Size = FSize(String(ModName)) then
            if CheckSum(String(ModName)) = Hash then
              inc(Result);
        end;
        CloseHandle(Process);
      end;
    end;
  end;
end;

La unit Hashes se puede encontrar aquí
http://www.clubdelphi.com/foros/showpost.php?p=171622&postcount=4

El hilo que dió origen a esto es el siguiente:
http://www.clubdelphi.com/foros/showthread.php?t=40902
Responder Con Cita