Lazarus: Terminate Windows process

Veröffentlicht von

Two examples how to quit processes in Windows.

KillProcess

The first method is to kill the process by name. You can do that with the following function.

procedure KillProcess(name: String);
var h:tHandle;
    pe:tProcessEntry32;
    sPrcName:string;
begin
  h:=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  try
    pe.dwSize:=SizeOf(pe);
    if Process32First(h,pe) then begin
      while Process32Next(h,pe) do
      begin
        sPrcName:=pe.szExeFile;
        if pos(LowerCase(name),LowerCase(sPrcName))>0 then
        begin
          TerminateProcess(OpenProcess(Process_Terminate, False, pe.th32ProcessID), 0);
        end;
      end;
    end
    else RaiseLastOSError;
  finally
  end;
end;

The „name“ parameter must be the process name, as shown in the task manager.

Send quit message to window

Another option is to send a Windows message to an application. This function can be used to close applications by the window name. It will first look up the window, get the application handle and then post the WM_QUIT message to that window.

function KillApp(const sCapt: PChar): boolean;
var AppHandle: THandle;
begin
  AppHandle:=FindWindow(Nil, sCapt);
  Result:=PostMessage(AppHandle, WM_QUIT, 0, 0);
end;

Kommentar hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert