原创哦...如果有更好的功能或者BUG修订请通知我, 谢谢
uses
TLHelp32, PsAPI;{AFile: 要结束的进程
AEffectFirst: 是否只结束第一个找到的进程可以只输入EXE名称, 或者全路径+文件名, 或者只是某个文件路径
如果输入的只是某个路径, 则关闭属于这个路径下的所有进程}
function KillProcess(AFile: string; AEffectFirst: Boolean = True): WORD; overload;
const
PROCESS_TERMINATE = $0001;
var
nContinueLoop: BOOL;
nSnapShotHandle: THandle;
nProcessEntry32: TProcessEntry32;
nSelfID, nPrHandle: Cardinal;
nMBF: array [0..MAX_PATH] of Char;
nCMode: Byte; {0:检测全路径文件, 1:仅检测文件 2:仅检测路径}
nCPath, nCFile, nStr, nFile, nPath: string;
begin
Result := 0;
AFile := UpperCase(AFile);
nCPath := ExtractFilePath(AFile);
nCFile := ExtractFileName(AFile);if (nPath <> ‘‘) and (nCFile <> ‘‘) then
nCMode := 0
else if nCFile <> ‘‘ then
nCMode := 1
else if nCPath <> ‘‘ then
nCMode := 2
else
Exit;nSelfID := GetCurrentProcessID;
nSnapShotHandle := CreateToolhelp32SnapShot(TH32CS_SNAPPROCESS, 0);
try
nProcessEntry32.dwSize := SizeOf(nProcessEntry32);
nContinueLoop := Process32First(nSnapShotHandle, nProcessEntry32);
while nContinueLoop do
begin
if nProcessEntry32.th32ProcessID <> nSelfID then
begin
nStr := UpperCase(nProcessEntry32.szExeFile);
nFile := ExtractFileName(nStr);
nPrHandle := OpenProcess(PROCESS_ALL_ACCESS, False, nProcessEntry32.th32ProcessID);
try
if nCMode <> 1 then
begin
nPath := ExtractFilePath(nStr);
if nPath = ‘‘ then
beginif GetModuleFileNameEx(nPrHandle, 0, @nMBF[0], SizeOf(nMBF)) > 0 then
nPath := UpperCase(ExtractFilePath(nMBF));
end;
end;if ((nCMode = 0) and (nPath = nCPath) and (nFile = nCFile)) {全路径文件名相同}
or ((nCMode = 1) and (nFile = nCFile)) {文件名相同}
or ((nCMode = 2) and (Copy(nPath, 1, Length(nCPath)) = nCPath)) {路径包含} then
begin
TerminateProcess(nPrHandle, 0); {强制关闭进程}
if AEffectFirst then
Break;
end;
finally
CloseHandle(nPrHandle);
end;
end;
nContinueLoop := Process32Next(nSnapShotHandle, nProcessEntry32);
end;
finally
CloseHandle(nSnapShotHandle);
end;
end;