Link to home
Start Free TrialLog in
Avatar of yewnix
yewnixFlag for United States of America

asked on

Process List in a Service Application

I'm trying to develop a service application that watches the processes that are currently running.
Everything I've tried so far with EnumWindows etc is not working inside the service application.

Could someone please give me an example of how to get the current list of running process into say a TStringList
within a Service Application ?
ASKER CERTIFIED SOLUTION
Avatar of Lukasz Zielinski
Lukasz Zielinski
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of yewnix

ASKER

Really didn't want to find something component related.
I have figured it out. Here is my findings.

procedure TService3.ServiceExecute(Sender: TService);
var
 I: Integer;
 Snapshot: THandle;
 processhandle : THandle;
 PE: TProcessEntry32;
begin
  while not Terminated do
  begin
    Snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (Snapshot = DWORD(-1)) then
      Exit;
    PE.dwSize := SizeOf(TProcessEntry32);
    if Process32First(Snapshot, PE) then
    repeat
      if Pe.szExeFile = 'notepad.exe' then
      begin
        ProcessHandle := OpenProcess(PROCESS_TERMINATE, FALSE, pe.th32ProcessID);
        TerminateProcess(ProcessHandle,4);
        CloseHandle(ProcessHandle);
      end;
    until not Process32Next(Snapshot, PE);
    CloseHandle (Snapshot);
    sleep(200);
    ServiceThread.ProcessRequests(False);
  end;
end;

procedure TService3.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
  ServiceThread.Terminate;
end;

---------------------------------
This will close notepad.exe anytime its started.
I appreciate your post so I will honor you the points as I will mostly likely use those in the future.
Thanks.
as you wish,
 with WMI you can execute notification query which will trigger each time specified process is spawned so you dont need to loop and check for notepad or any other process
anyway thanks for points.
ziolko.