/*Title:Delphi進程,模塊相關編程
*Author:Insun
*Blog:http://yxmhero1989.blog.163.com
*From:www.4safer.com
*/
個人覺得Delphi進程相關可以按照下面幾點來研究,有亂點之處請不吝指正(有點代碼寫的的確很糟糕,雖然金山和卡巴也有代碼臨時工嫌疑,style不行就是囧):
我們查看了TLHELP32: 發現有下面5個數據結構
Shapshot function
heap walking
process walking
Thread walking
Module walking
I.列出進程相關:進程名,PID,父進程ID,模塊ID,引用計數,線程計數,優先權,進程默認堆棧,進程文件
路徑 <這個操作很簡單,網上源碼到處都是,綜合一下成最好最厚道最全面的>
function GetPathFileofModule(ModuleName:String):String; //delphi 通過進程名獲得文件全路徑的函數
var
hProcSnap: THandle;
pProcess: THandle;
pe32: TProcessEntry32;
buf:array[0..MAX_PATH] of char;
hMod:HMODULE;
cbNeeded:DWORD;
begin
hProcSnap := CreateToolHelp32SnapShot(TH32CS_SNAPALL, 0);
if hProcSnap = INVALID_HANDLE_VALUE then Exit;
pe32.dwSize := SizeOf(ProcessEntry32);
if Process32First(hProcSnap, pe32) = True then
while Process32Next(hProcSnap, pe32) = True do
begin
if uppercase(pe32.szExeFile)=uppercase(ModuleName) then
begin
pProcess:=OpenProcess(PROCESS_QUERY_INFORMATION or
PROCESS_VM_READ,
FALSE,
pe32.th32ProcessID);
if pProcess<>0 then
begin
if EnumProcessModules( pProcess,@hMod,sizeof(hMod),cbNeeded) then
begin
ZeroMemory(@buf,MAX_PATH+1);
GetModuleFileNameEx(pProcess, hMod,buf,MAX_PATH+1);//枚舉進程文件所在路徑
Result:=strpas(buf);
end;
end;
end;
end;
CloseHandle(hProcSnap);
end;
procedure TForm1.ViewProcess; //關鍵代碼。uses TLHelp32, PsAPI,
var
hSnap,h : THandle;
ProcessEntry : TProcessEntry32;
Proceed : Boolean;
hMod:HMODULE;
cbNeeded,p:DWORD;
begin
hSnap := CreateToolhelp32Snapshot( TH32CS_SNAPALL , 0 ); //創建系統快照
if HSnap <> -1 then
begin
ProcessEntry.dwSize := SizeOf(TProcessEntry32); //先初始化 FProcessEntry32 的大小
Proceed := Process32First(hSnap, ProcessEntry);
// p :=DWORD(ListView1.Items.Objects[ListView1.itemindex]);
//h := OpenProcess(PROCESS_ALL_ACCESS, false, p); //p 為 進程ID
// if h > 0 then
// begin
//if EnumProcessModules( h, @hMod, sizeof(hMod), cbNeeded) then //查找第一個進程
while Proceed do //while 循環
begin
with ProcessEntry do
with listview1.Items.Add do
begin
caption:=szExeFile;
subitems.Add(inttostr(Th32ProcessID));
subitems.Add(inttostr(th32ParentProcessID));
subitems.Add(inttostr(Th32ModuleID));
subitems.Add(inttostr(cntUsage));
subitems.Add(inttostr(cntThreads));
subitems.Add(inttostr(pcPriClassBase));
subitems.Add(inttostr(th32DefaultHeapID));
// subitems.Add(ProcessEntry.szExePath);
subitems.Add(GetPathFileofModule(szExeFile));
end;
Proceed := Process32Next( hSnap, ProcessEntry); //查找下一個進程
end;
CloseHandle( hSnap );
CloseHandle(h);
self.Label1.Caption:=當前系統共有++inttostr(listview1.Items.count)++個進程 ;
end
else
ShowMessage( Oops... + SysErrorMessage(GetLastError));
end;
procedure TForm1.GetModule(pid: integer);
var th32handle:THandle;procstruct:TModuleEntry32;
finded:boolean;
begin
th32handle:=CreateToolHelp32Snapshot(TH32CS_SNAPMODULE,pid);
try
procstruct.dwSize:=sizeof(procstruct);
ListView2.Clear;
finded:=Module32First(th32handle,procstruct);
while finded do
begin
with ListView2.Items.Add do
&nb