如何获取包含我的应用程序创建的所有线程的列表

Joh*_*mas 8 windows delphi multithreading process

我想从我的应用程序中获取包含所有线程(主要的GUI线程除外)的列表,以便对它们执行一些操作.(设置优先级,杀死,暂停等)如何做到这一点?

RRU*_*RUZ 12

另一个选项是使用CreateToolhelp32Snapshot,Thread32FirstThread32Next函数.

看到这个非常简单的例子(在Delphi 7和Windows 7中测试过).

program ListthreadsofProcess;

{$APPTYPE CONSOLE}

uses
  PsAPI,
  TlHelp32,
  Windows,
  SysUtils;

function GetTthreadsList(PID:Cardinal): Boolean;
var
  SnapProcHandle: THandle;
  NextProc      : Boolean;
  TThreadEntry  : TThreadEntry32;
begin
  SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); //Takes a snapshot of the all threads
  Result := (SnapProcHandle <> INVALID_HANDLE_VALUE);
  if Result then
  try
    TThreadEntry.dwSize := SizeOf(TThreadEntry);
    NextProc := Thread32First(SnapProcHandle, TThreadEntry);//get the first Thread
    while NextProc do
    begin
      if TThreadEntry.th32OwnerProcessID = PID then //Check the owner Pid against the PID requested
      begin
        Writeln('Thread ID      '+inttohex(TThreadEntry.th32ThreadID,8));
        Writeln('base priority  '+inttostr(TThreadEntry.tpBasePri));
        Writeln('');
      end;

      NextProc := Thread32Next(SnapProcHandle, TThreadEntry);//get the Next Thread
    end;
  finally
    CloseHandle(SnapProcHandle);//Close the Handle
  end;
end;

begin
  { TODO -oUser -cConsole Main : Insert code here }
  GettthreadsList(GetCurrentProcessId); //get the PID of the current application
  //GettthreadsList(5928);
  Readln;
end.
Run Code Online (Sandbox Code Playgroud)


vcl*_*per 5

您可以使用我的TProcessInfo类:

var
  CurrentProcess : TProcessItem;
  Thread : TThreadItem;
begin
  CurrentProcess := ProcessInfo1.RunningProcesses.FindByID(GetCurrentProcessId);
  for Thread in CurrentProcess.Threads do
    Memo1.Lines.Add(Thread.ToString);
end;
Run Code Online (Sandbox Code Playgroud)