Mega Code Archive

 
Categories / Delphi / API
 

How to kill a running applicaton using the file name

This article will help you find and kill a running application by using the filename that is running. don't forget to add Tlhelp32 unit in the uses clause. please note this code has been only tested on windows 2000, I don't know if it will work on windows 95/98, but if it does work please email me. uses Tlhelp32; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); private { Private declarations } function KillTask(ExeFileName: string): integer; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} function TForm1.KillTask(ExeFileName: string): integer; const PROCESS_TERMINATE=$0001; var ContinueLoop: BOOL; FSnapshotHandle: THandle; FProcessEntry32: TProcessEntry32;//used to store proccess information that are //currently running sFileName:string; begin result := 0; //Takes a snapshot of the processes and the heaps, modules, and threads //used by the processes FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); FProcessEntry32.dwSize := Sizeof(FProcessEntry32); //Retrieves information about the first process encountered in a system snapshot ContinueLoop := Process32First(FSnapshotHandle,FProcessEntry32); //stops until there is no more processes to check while integer(ContinueLoop) <> 0 do begin sFileName:= UpperCase(ExtractFileName(FProcessEntry32.szExeFile)); //check if filename is the same to terminate it. if (sFileName=UpperCase(ExeFileName)) then Result := Integer(TerminateProcess(OpenProcess( PROCESS_TERMINATE, BOOL(0), FProcessEntry32.th32ProcessID), 0)); //gets the next process encountered in a system snapshot ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32); end; CloseHandle(FSnapshotHandle); end; procedure TForm1.Button1Click(Sender: TObject); begin KillTask('itemfinder.exe'); end;