User Tools

Site Tools


codesamples:getcallingprocesses

Get the calling processes (father processes)

using System.Diagnostics
using System.Runtime.InteropServices

function Start( ) as void                          
local oProcess as Process
local nID as int
local cProcessName as string
	
oProcess := Process.GetCurrentProcess()
nId := oProcess:Id                                                    
while nId > 0                
  try                                            
  oProcess := Process.GetProcessById( nId )
  if oProcess == null
    cProcessName := "< no Process >"
  else
    cProcessName := oProcess:ProcessName
  endif
  System.Console.WriteLine( String.Format( "ProcessID {0}, ProcessName {1}", nID:ToString(), cProcessName ) )
  nId := Utility.GetParentProcessId( nId )
  catch
  nId := 0
  end try
end
	
return       

static class Utility
	
static method GetParentProcessId( nId as int ) as int
local nParentId as int
local oHandle as IntPtr
local oProcInfo as PROCESSENTRY32

nParentId := 0	
oHandle := WindowsAPI.CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, dword( nId ) )
if oHandle != IntPtr.Zero
  oProcInfo := PROCESSENTRY32{}
  oProcInfo.dwSize := dword( System.Runtime.InteropServices.Marshal.SizeOf( typeof( PROCESSENTRY32 ) ) )
  System.Console.WriteLine( String.Format( "Size is {0}", oProcInfo:dwSize:ToString() ) )
  if WindowsAPI.Process32First( oHandle, oProcInfo ) 
    while nId != oProcInfo.th32ProcessID .and. WindowsAPI.Process32Next( oHandle, oProcInfo )
    end
    if nId == oProcInfo.th32ProcessID
      nParentId := int( oProcInfo.th32ParentProcessID )
    endif
  endif
endif
	
return nParentId
	
end class

static class WindowsAPI
	
[DllImport("kernel32.dll",SetLastError:= true,EntryPoint:="CreateToolhelp32Snapshot")];
static method CreateToolhelp32Snapshot( dwFlags as dword, th32ProcessID as dword ) as IntPtr
 
[DllImport("kernel32.dll",EntryPoint:="Process32First")];
static method Process32First( hSnapshot as IntPtr, oEntry ref PROCESSENTRY32 ) as logic
 
[DllImport("kernel32.dll",EntryPoint:="Process32Next")];
static method Process32Next( hSnapshot as IntPtr, oEntry ref PROCESSENTRY32 ) as logic

end class
define TH32CS_SNAPPROCESS := 2 as dword     
define TH32CS_SNAPMODULE := 8 as dword

[StructLayout(LayoutKind.Sequential)];
structure PROCESSENTRY32 
	dwSize as dword
	cntUsage as dword
	th32ProcessID as dword
	th32DefaultHeapID as IntPtr
	th32ModuleID as dword
	cntThreads as dword
	th32ParentProcessID as dword
	pcPriClassBase as int
	dwFlags as dword
//	szExeFile[260] as byte
  	[MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)] szExeFile as string
    
end structure
codesamples/getcallingprocesses.txt · Last modified: 2018/05/23 09:53 by wolfgangriedmann