在Delphi中用ListBox顯示進程列表以及取得指定進程的EXE路徑的代碼,大家在uses中加入TLHelp32,PsAPI;
//ListBox顯示進程列表
procedure TForm1.Button1Click(Sender: TObject);
var lppe: TProcessEntry32;
found : boolean;
Hand : THandle;
P:DWord;
s:string;
begin
ListBox1.Items.Clear ;
Hand := CreateToolhelp32Snapshot(TH32CS_SNAPALL,0);
found := Process32First(Hand,lppe);
while found do
begin
s := StrPas(lppe.szExeFile);
if lppe.th32ProcessID>0 then
p := lppe.th32ProcessID
else
p := 0;
ListBox1.Items.AddObject(s,pointer(p));//列出所有進程。
found := Process32Next(Hand,lppe);
end;
end;
//取得進程EXE路徑
procedure TForm1.Button2Click(Sender: TObject); //uses PSAPI;
var
h:THandle; fileName:string; iLen:integer; hMod:HMODULE;cbNeeded,p:DWord;
begin
p :=DWord(ListBox1.Items.Objects[ListBox1.itemindex]);
h := OpenProcess(PROCESS_ALL_Access, false, p); //p 為 進程ID
if h > 0 then
begin
if EnumProcessModules( h, @hMod, sizeof(hMod), cbNeeded) then
begin
SetLength(fileName, MAX_PATH);
iLen := GetModuleFileNameEx(h, hMod, PCHAR(fileName), MAX_PATH);
if iLen <> 0 then
begin
SetLength(fileName, StrLen(PCHAR(fileName)));
ShowMessage(fileName);
end;
end;
CloseHandle(h);
end;
end;
運行效果: