How to get information about a process?  Download
This page presents a Delphi 7 function that retrieves the properties of a process running on a local or remote computer. It is based on TWmiQuery component from WmiSet component collection. Almost the same information (plus some extras) may be retrieved using TWmiProcessControl component. The only reason why TWmiQuery is used here is that it provides the convenient method to iterate through the process' properties.

The source code below creates and destroys the components on the fly, so it may be used UI- and in console-type applications.


// this function prints out the information about a running process 
// It may be used for local or remote host. When used for local host 
// TargetHost, UserName, Password parameters must be empty. 
// For remote computer the parameters must be: 
// TargetHost: name or IP address of the remote host, like '10.8.36.54' 
// UserName: name of the user, may include domain, like 'MOON\Administrator'; 
// Password: the user's password. 
// AProcess: either a name (as returned by process_enumerate_query.exe example) 
//           or a handle of process (integer value); 
procedure ProcessGetInfo(TargetHost, UserName, Password, AProcess: string);
var
  Connection: TWmiConnection;
  Query: TWmiQuery;
  vProcessFound: boolean;
  i: integer; 
begin
  Query      := TWmiQuery.Create(nil);
  Connection := TWmiConnection.Create(nil);
  try
    Query.Connection := Connection;
    Query.WQL.Text := 'select * from Win32_Process';
    Connection.MachineName := TargetHost;
    Connection.Credentials.UserName := UserName;
    Connection.Credentials.Password := Password;

    // exception may happen on Win9x, WinNT if WMI core is not installed; 
    // The provided credentials may also be invalid. 
    Connection.Connected := true;

    Query.Open;
    if (StrToIntDef(AProcess, -1) <> -1) then
      vProcessFound := Query.Locate('Handle', AProcess, [])
      else vProcessFound := Query.Locate('Name', AProcess, []);

    if vProcessFound then
    begin
      for i := 0 to Query.Fields.Count - 1 do
        writeln(Query.Fields[i].FieldName + ': '+ Query.Fields[i].AsString);
    end else
    begin
      raise Exception.Create('Specified process not found.');
    end;
  finally
    Query.Free;
    Connection.Free;
  end;
end;