Hi Experts,
I've been trying to terminate a system process programmatically via Delphi with the following code:
function KillTask(ExeFileName: string): integer;
const
PROCESS_TERMINATE=$0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
result := 0;
FSnapshotHandle := CreateToolhelp32Snapshot(T
H32CS_SNAP
PROCESS, 0);
FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHa
ndle, FProcessEntry32);
while integer(ContinueLoop) <> 0 do begin
if (StrIComp(PChar(ExtractFil
eName(FPro
cessEntry3
2.szExeFil
e)), PChar(ExeFileName)) = 0)
or (StrIComp(FProcessEntry32.
szExeFile,
PChar(ExeFileName)) = 0) then
Result := Integer(TerminateProcess(O
penProcess
(
PROCESS_TERMINATE, BOOL(0), // BOOL(0) means 'false'
FProcessEntry32.th32Proces
sID), 0));
ContinueLoop := Process32Next(FSnapshotHan
dle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandl
e);
end;
However, the above codes only works for programs/processes that are running under the 'normal' user account. The process that I'm trying to stop is being run with the system account. I did some research and found that some privilege settings needs to be done, so I've included the following procedure and called it before running the KillTask method:
procedure KillPrivilege;
var
DebugValue: TLargeInteger;
tkp: TTokenPrivileges;
PreviousState: TTokenPrivileges;
dw: DWORD;
h: THandle;
begin
OpenProcessToken(GetCurren
tProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, h);
LookupPrivilegeValue(nil, 'SeDebugPrivilege', DebugValue);
dw := 0;
tkp.PrivilegeCount := 1;
tkp.Privileges[0].Luid := DebugValue;
tkp.Privileges[0].Attribut
es := SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(h, false, tkp, 0, PreviousState, dw);
end;
But the process is still not terminated as expectedly. Fyi, the above set of codes are obtained from experts-exchange as well. Is there an error in the codes, or did I mis-typed anything?