` Printed Icetips Article

Icetips Article



Par2: How to detect if an exe is running
2011-08-26 -- Jens Matschke
 
MODULE('Windows.DLL')
  CreateToolhelp32Snapshot(ULONG,ULONG),UNSIGNED,PASCAL,RAW
  Process32First(UNSIGNED,UNSIGNED),BOOL,PASCAL,RAW
  Process32Next(UNSIGNED,UNSIGNED),BOOL,PASCAL,RAW
  CloseHandle(UNSIGNED),BOOL,PASCAL,RAW
END

I've created a small source procedure to check if a process is running.

Simply call: isrunning#=IsProcessRunning('someprocess.exe')

This is the code for it:


IsProcessRunning     PROCEDURE  (PProcess) !PProcess parameter of type STRING
RVal                 BYTE
locProcessName       &CSTRING
hProcessSnap         UNSIGNED
pe32                 GROUP,PRE()
dwSize                 ULONG
cntUsage               ULONG
th32ProcessID          ULONG
th32DefaultHeapID      ULONG
th32ModuleID           ULONG
cntThreads             ULONG
th32ParentProcessID    ULONG
pcPriClassBase         LONG
dwFlags                ULONG
szExeFile              CSTRING(260)
                     END
TH32CS_SNAPPROCESS   EQUATE(02H)

  CODE
  RVal=False

  locProcessName &= NEW(CSTRING(LEN(CLIP(PProcess))+1))
  locProcessName=UPPER(CLIP(PProcess))

  hProcessSnap=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0)
  IF hProcessSnap=-1 !INVALID_HANDLE_VALUE
    !MESSAGE('Failed to create process snapshot','Error!')
  ELSE
    pe32.dwsize=SIZE(pe32)
    
    !Count the number of running processes
    IF Process32First(hProcessSnap,ADDRESS(pe32))
      IF UPPER(pe32.szExeFile)=locProcessName
        RVal+=1
      .
      LOOP
        pe32.dwsize=SIZE(pe32)
        IF Process32Next(hProcessSnap,ADDRESS(pe32))
          IF UPPER(pe32.szExeFile)=locProcessName
            RVal+=1
          .
        ELSE
          BREAK
        .
      .
    .
    !IF RVal=1     !process is running     (1 instance)
    !
    !ELSIF RVal>=2 !process is running     (more than 1 instance -> "RVal" instances)
    !
    !ELSIF RVal=0  !process is not running
    !
    !.
    
    IF CloseHandle(hProcessSnap)=0
      !MESSAGE('Error ' & shd_GetLastError() & ' closing process snapshot
handle','Error!')
    .
  .
  DISPOSE(locProcessName)
  RETURN RVal



Printed November 21, 2024, 6:45 am
This article has been viewed/printed 35254 times.