Re: monitor NT processesPosted by webmaster Guido on December 07, 2001: In Reply to: monitor NT processes posted by Stefan Loeners on December 02, 2001: : Is there any way the processes (not the applications) running on NT can be listed? : Thank you (also for having answered my previous questions). ----------- On Borland's site, I found the function RunningProcessesList, that fills a TStrings object with the running modules file names. Depending on the Windows version, it uses PSAPI functions or TOOLHELP. I just restructured the code a little bit, but I didn't make any drastic changes. If you have any problems with it, just let me know. But please, no questions about "how" it works, because that's far beyond DelphiLand's "for beginners" philosophy ;-) The function works with all versions of Windows (95/98/NT4/2000). I tested it under Delphi 4 and 5 (and normally it should also run on D6).
uses TLHelp32, PsApi; function BuildListPS(List: TStrings): Boolean; var PIDs: array[0..1024] of DWORD; Handle: THandle; Needed: DWORD; i: integer; ModuleFileName: array[0..MAX_PATH] of char; begin Result := EnumProcesses(@PIDs, Sizeof(PIDs), Needed); if Result then begin for i := 0 to (Needed div Sizeof(DWORD)) - 1 do begin if PIDs[i] <> 0 then begin Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PIDs[I]); if Handle <> 0 then begin if GetModuleFileNameEx(Handle, 0, ModuleFileName, Sizeof(ModuleFileName)) = 0 then List.AddObject('[System]', Pointer(INVALID_HANDLE_VALUE)) else List.AddObject(ModuleFileName, Pointer(PIDs[I])); end; // if Handle CloseHandle(Handle); end; // if PIDs[i] end; // for end; // if Result end; function BuildListTH(List: TStrings): Boolean; var SnapProcHandle: THandle; ProcEntry: TProcessEntry32; NextProc: Boolean; begin SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); Result := SnapProcHandle <> THandle(-1); if Result then begin ProcEntry.dwSize := Sizeof(ProcEntry); NextProc := Process32First(SnapProcHandle, ProcEntry); while NextProc do begin List.AddObject(ProcEntry.szExeFile, Pointer(ProcEntry.th32ProcessID)); NextProc := Process32Next(SnapProcHandle, ProcEntry); end; CloseHandle(SnapProcHandle); end; // if Result end; function RunningProcessesList(List: TStrings): Boolean; begin List.BeginUpdate; try List.Clear; if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion = 4) then Result := BuildListPS(List) else Result := BuildListTH(List); finally List.EndUpdate; end; end; To test it, just drop a TListBox and a TButton on a form, and create an event handler for the button: procedure TForm1.Button1Click(Sender: TObject); begin RunningProcessesList(ListBox1.Items); end;
|