如何使用Delphi在我的机器上获取正在运行的进程列表(包含PID,所有者等的详细信息)?
编辑:所提出的解决方案都没有给我拥有该进程的用户,只有PID,ExeName等信息......
一种方法是使用工具帮助库(见TlHelp32单元),或EnumProcesses在Windows NT(见PSAPI单位).看一看JclSysInfo.RunningProcessesList
在JCL的一个例子.
以下是如何获取进程用户名的快速示例:
type PTokenUser = ^TTokenUser; TTokenUser = packed record User: SID_AND_ATTRIBUTES; end; function GetProcessUserName(ProcessID: Cardinal; out DomainName, UserName: string): Boolean; var ProcessHandle, ProcessToken: THandle; InfoSize, UserNameSize, DomainNameSize: Cardinal; User: PTokenUser; Use: SID_NAME_USE; _DomainName, _UserName: array[0..255] of Char; begin Result := False; DomainName := ''; UserName := ''; ProcessHandle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, ProcessID); if ProcessHandle = 0 then Exit; try if not OpenProcessToken(ProcessHandle, TOKEN_QUERY, ProcessToken) then Exit; try GetTokenInformation(ProcessToken, TokenUser, nil, 0, InfoSize); User := AllocMem(InfoSize * 2); try if GetTokenInformation(ProcessToken, TokenUser, User, InfoSize * 2, InfoSize) then begin DomainNameSize := SizeOf(_DomainName); UserNameSize := SizeOf(_UserName); Result := LookupAccountSid(nil, User^.User.Sid, _UserName, UserNameSize, _DomainName, DomainNameSize, Use); if Result then begin SetString(DomainName, _DomainName, StrLen(_DomainName)); SetString(UserName, _UserName, StrLen(_UserName)); end; end; finally FreeMem(User); end; finally CloseHandle(ProcessToken); end; finally CloseHandle(ProcessHandle); end; end;