Close Window via TerminateProcess - Delphi

Description

Terminating the Window’s Owning Process (not only window)

DarkCoderSc personal avatar
DarkCoderSc

Jean-Pierre LESUEUR

var ATargetWindow := FindWindow(nil, 'Untitled - Notepad');
if ATargetWindow = 0 then
    Exit();

var AProcessId : Cardinal;
if GetWindowThreadProcessId(ATargetWindow, AProcessId) = 0 then
  raise EWindowsException.Create('GetWindowThreadProcessId');

var hProcess := OpenProcess(PROCESS_ALL_ACCESS, False, AProcessId);
if hProcess = 0 then
  raise EWindowsException.Create('OpenProcess');
try
  if not TerminateProcess(hProcess, 0) then
    raise EWindowsException.Create('TerminateProcess');
finally
  CloseHandle(hProcess);
end;

Creating and researching code snippets takes time and effort. You’re welcome to share them through your own platforms, but please don’t forget to credit the original author, here: Jean-Pierre LESUEUR.


Created

April 24, 2025

Last Revised

April 24, 2025