開發安全工具、進程管理器或反流氓軟體模組時,核心能力是**枚舉系統進程**並**強制終結指定進程**。本文深度解析 Delphi 使用 Toolhelp32 API 實現進程遍歷與終結的完整代碼邏輯。
CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0):建立系統進程快照Process32First/Next:遍歷快照中的 TProcessEntry32 記錄OpenProcess(PROCESS_TERMINATE, False, PID):取得終結權限控制代碼TerminateProcess(hProcess, 0):強制結束進程const
PROCESS_TERMINATE = $0001; // OpenProcess 權限旗標
TH32CS_SNAPPROCESS = $00000002; // 快照旗標:進程列表
// TProcessEntry32 (Windows.pas 已定義,關鍵欄位)
type
TProcessEntry32 = record
dwSize: DWORD; // 必須先設定為 SizeOf(TProcessEntry32)
cntUsage: DWORD;
th32ProcessID: DWORD; // 進程 ID (PID)
th32DefaultHeapID: DWORD;
th32ModuleID: DWORD;
cntThreads: DWORD;
th32ParentProcessID: DWORD;
pcPriClassBase: LONG;
dwFlags: DWORD;
szExeFile: array[0..MAX_PATH-1] of Char; // 可執行檔名稱
end;
procedure TForm1.EndProcess(const AFileName: string);
var
Snapshot: THandle;
ProcEntry: TProcessEntry32;
ContinueLoop: BOOL;
ProcHandle: THandle;
TargetName: string;
begin
TargetName := LowerCase(ExtractFileName(AFileName)); // 僅比對檔名,不含路徑
Snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if Snapshot = INVALID_HANDLE_VALUE then begin
ShowMessage('建立進程快照失敗: ' + SysErrorMessage(GetLastError));
Exit;
end;
try
ProcEntry.dwSize := SizeOf(ProcEntry);
ContinueLoop := Process32First(Snapshot, ProcEntry);
while ContinueLoop do begin
// 比對檔名 (不分大小寫)
if LowerCase(ProcEntry.szExeFile) = TargetName then begin
// 取得終結權限
ProcHandle := OpenProcess(PROCESS_TERMINATE, False, ProcEntry.th32ProcessID);
if ProcHandle <> 0 then begin
try
if TerminateProcess(ProcHandle, 0) then
ShowMessage(Format('已終結進程: %s (PID=%d)', [TargetName, ProcEntry.th32ProcessID]))
else
ShowMessage('終結失敗 (權限不足): ' + SysErrorMessage(GetLastError));
finally
CloseHandle(ProcHandle);
end;
end else begin
ShowMessage('無法開啟進程 (權限不足): ' + SysErrorMessage(GetLastError));
end;
// 可選:break 只終結第一個,或繼續終結所有同名進程
end;
ContinueLoop := Process32Next(Snapshot, ProcEntry);
end;
finally
CloseHandle(Snapshot); // 必須釋放快照控制代碼
end;
end;
procedure TForm1.ScanAndClean;
const
// 知名流氓軟體進程名稱特徵 (示例)
RoguePatterns: array[0..4] of string = (
'adware', 'spyware', 'toolbar', 'hijack', 'miner'
);
var
Snapshot: THandle;
ProcEntry: TProcessEntry32;
ContinueLoop: BOOL;
ProcName: string;
IsRogue: Boolean;
I: Integer;
begin
Memo1.Lines.Add('開始掃描可疑進程...');
Snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if Snapshot = INVALID_HANDLE_VALUE then Exit;
try
ProcEntry.dwSize := SizeOf(ProcEntry);
ContinueLoop := Process32First(Snapshot, ProcEntry);
while ContinueLoop do begin
ProcName := LowerCase(ProcEntry.szExeFile);
IsRogue := False;
for I := Low(RoguePatterns) to High(RoguePatterns) do
if Pos(RoguePatterns[I], ProcName) > 0 then begin
IsRogue := True;
Break;
end;
if IsRogue then begin
Memo1.Lines.Add(Format('發現可疑: %s (PID=%d)', [ProcName, ProcEntry.th32ProcessID]));
// 實際清除需使用者確認,此處僅示範
// EndProcess(ProcName);
end;
ContinueLoop := Process32Next(Snapshot, ProcEntry);
end;
Memo1.Lines.Add('掃描完成。');
finally
CloseHandle(Snapshot);
end;
end;
{$SETPEFLAGS IMAGE_FILE_LARGE_ADDRESS_AWARE} 或編譯為 64-bit 才能正確枚舉 64-bit 進程WM_CLOSE 或 CTRL_CLOSE_EVENT 讓進程自行清理,TerminateProcess 為最後手段 (資料遺失風險)掌握 Toolhelp32 API 進行進程枚舉與終結,是 Delphi 系統級編程的基本功。配合特徵庫、白名單、權限提升、優雅關閉策略,即可構建專業級進程管理與安全防護模組。