procedure TForm1.EnumProcess(const List:TstringList);
var
PInfo:TProcInfo;
ProEntry:TagProcessEntry32;
Handle:cardinal;
ISNext:Boolean;
begin
IsNext:=True;
Handle:=TlHelp32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
TlHelp32.Process32First(Handle,ProEntry);
while ISNext do
  begin
    PInfo:=TProcInfo.Create;
    PInfo.FExeName:=ProEntry.szExeFile;
    PInfo.FPID:=ProEntry.th32ProcessID;
    ISNext:=Process32Next(Handle,ProEntry);
    //Edit1.Text:=InttoStr(GetLastError);    一定要加这串代码,才能枚举进程,我想不明白啊,注释了就不能枚举 
    List.AddObject(InttoStr(ProEntry.th32ProcessID),PInfo);
  end;
end;procedure TForm1.FormShow(Sender: TObject);
begin
ListView1.Columns[0].Caption:='影象名称';
ListView1.Columns[1].Caption:='PID';
end;procedure TForm1.Button1Click(Sender: TObject);
var
I,J,Index:Integer;
AItem:TListItem;
AList:TstringList;
PInfo:TProcInfo;
begin
AItem:=TListItem.Create(nil);
AList:=TStringList.Create;
EnumProcess(AList);
J:=0;
for I:=0 to ListView1.Items.Count-1 do
  begin
    AItem:=ListView1.Items[J];
    Index:=AList.IndexOf(AItem.SubItems.Strings[0]);
    if Index<>-1 then
      begin
        PInfo:=TProcInfo(AList.Objects[Index]);
        AItem.SubItems.Strings[0]:=InttoStr(PInfo.FPID);
        AItem.Caption:=PInfo.FExeName;
        AList.Delete(J);
        INC(J);
      end else
        begin
          ListView1.Items.Delete(J);
        end;
  end;
for I:=0 to AList.Count-1 do
  begin
    AItem:=ListView1.Items.Add;
    AItem.SubItems.Add(InttoStr(TProcInfo(AList.Objects[I]).FPID));
    AItem.Caption:=TProcInfo(AList.Objects[I]).FExeName;
  end;
end;我枚举进程的时候,没有成功,本想用GetlastError查查看是为什么,没有想到枚举进程成功了,去掉又不行,郁闷啊

解决方案 »

  1.   

        ISNext:=Process32Next(Handle,ProEntry); 
        //Edit1.Text:=InttoStr(GetLastError);    一定要加这串代码,才能枚举进程,我想不明白啊,注释了就不能枚举 
        List.AddObject(InttoStr(ProEntry.th32ProcessID),PInfo);
    改成:
        List.AddObject(InttoStr(ProEntry.th32ProcessID),PInfo);
        ISNext:=Process32Next(Handle,ProEntry);  
    试一下...
      

  2.   

    procedure TForm1.EnumProcess(const List:TstringList);
    var
      hSnap : THandle;
      pe32 : TProcessEntry32;
    begin
      hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
      if INVALID_HANDLE_VALUE <> hSnap then
      try
        pe32.dwSize := sizeof(TProcessEntry32);
        if Process32First(hSnap, pe32) then
        repeat
          List.Add(pe32.szExeFile);
        until not Process32Next(hSnap, pe32);
      finally
        CloseHandle(hSnap);
      end;
    end;
    //--------------------------
    procedure TForm1.Button7Click(Sender: TObject);
    var
      List : TStringList;
      i : Integer;
    begin
      List := TStringList.Create;  EnumProcess(List);
      Memo2.Clear;  for i := 0 to List.Count - 1 do
       Memo2.Lines.Add(List.Strings[i]);  FreeAndNil(List);
    end;
      

  3.   

    通常这种情况说明,上一语句(Process32Next)的执行需要一定的延时才有返回的